单件模式(java)

一:(⊙_⊙;)单例模式(Singleton Pattern):单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。

二:单例模式的要点有三个:
1 某个类只能有一个实例;
2 是它必须自行创建这个实例;
3 是它必须自行向整个系统提供这个实例。

三:类图

这里写图片描述

四:

//“懒汉式”:
public class Singleton{
     //静态成员记录唯一实例
     private static Singleton uniqueInstance;
     //把构造器申明为私有的,只有自己类才能实例化
     private Singleton(){
     }
     //入口处
     public static Singleton getInstance(){
         if(uniqueInstance==null){
              uniqueInstance=new Singleton();
         }
         return uniqueInstance;
     }

}

线程不安全! 解决办法:使用同步机制

class Singleton {
    private static Singleton instance = null;
    private Singleton(){}
    public static Singleton getInstance(){
        if(instance==null){
        //Singleton.class 作为锁,对象必须是单一的,根据反射可知返回的为Singleton类的对象
            synchronized(Singleton.class){
                if(instance == null){
                    instance=new Singleton();
                }   
            }
        return instance;
    } 
}
public class TestSingleton{
    public static void main(String[] args){
        Singleton s1=Singleton.getInstance();
        Singleton s2=Singleton.getInstance();
        System.out.println(s1==s2);
    }   
}

实验:提示:学生的学号生成方案,是在学生注册后,通过录入学生的基本信息,包括入学学年、学院、专业、班级等信息后,保存相应的资料后自动生成的。学号生成器的业务算法为:

入学学年(2位)+学院代码(2位)+专业代码(2位)+班级代码(2位)+序号(2位)

//Client.java
public class Client {
    public static void main(String[] args) {
        Student.getClient().setStudentNo("2015","计算机学院","软件工程","二班","01");
    System.out.println(Student.getClient().getStuNo());
    }
}
//Student.java
public class Student {
 private static Student client=null;
 private String studentno;

 private String xn;
 private String xy;
 private String zy;
 private String bj;
 private String xh;

 private Student(){};
 //获取单一实例
 int i=1;
 public synchronized static Student getClient(){
     if(client==null){
         client=new Student();   
     }
     return client;
 }
 public  void  setStudentNo(String xn,String xy,String zy,String bj,String xh){
     this.xn=xn;
     this.xy=xy;
     this.zy=zy;
     this.bj=bj;
     this.xh=xh;
 }
 public String getStuNo(){
     //分配原则
     //入学学年(2位)+学院代码(2位)+专业代码(2位)+班级代码(2位)+序号(2位)
     if(xn=="2015")
         xn="15";
     if(xy=="计算机学院")
         xy="10";
     if(zy=="软件工程")
         zy="11";
     if(bj=="二班")
         bj="02";


     studentno=xn+xy+zy+bj+xh;
     return studentno;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值