qwb0614

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

实验7:单例模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解单例模式的动机,掌握该模式的结构;

2、能够利用单列模式解决实际问题。

 
   

 


[实验任务一]:学号的单一

仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。

实验要求:

1.  画出对应的类图;

 

 

2.提交源代码;

3.注意编程规范。

 

package ruanjiansheji.shiyan7;

public class Client {
    public static void main(String[] args) {
        Student no1,no2;
        no1=Student.getInstance();
        no2=Student.getInstance();
        System.out.println("身份是否一致:"+(no1==no2));

        String id1,id2;
        id1=no1.getStudentId();
        id2=no2.getStudentId();
        System.out.println("第一次申请学号:"+ id1);
        System.out.println("第二次申请学号:"+ id2);
        System.out.println("学号是否一样:"+ id1.equalsIgnoreCase(id2));
        System.out.println("是否是相同对象:"+ (id1 == id2));
    }
}
package ruanjiansheji.shiyan7;



public class Student {
    private static Student instance =null;
    private String Id;
    private Student(){}
    public static Student getInstance(){
        if(instance == null){
            System.out.println("第一次申请,分配学号");
            instance = new Student();
            instance.setStudentId(String.valueOf(System.currentTimeMillis()));
        }else {
            System.out.println("获取旧学号");
        }
        return instance;
    }

    private void setStudentId(String valueOf) {
        this.Id=valueOf;
    }
    public String getStudentId() {
        return this.Id;
    }
}

 

posted on 2023-11-20 08:12  嘎嘎鸭1  阅读(9)  评论(0)    收藏  举报