java单例模式(类只能创建唯一对象)

时间:2021-12-14 20:48:49
 1 //饿汉式
 2 class  Single
 3 {
 4    private static final Single s= new Single();
 5    private Single(){}
 6    public static Single getInstance()
 7       {
 8           return s;
 9       }      
10 }
11 //懒汉式
12 class  Single
13 {
14    private static Single s=null;
15    private Single(){}
16    public static Single getInstance()
17  {
18       if(s==null)//解决效率问题
19    {
20       synchronized(single.class)//解决线程安全问题
21       {
22          if(s==null)
23          s=new Single();
24          return s;
25       }  
26    }   
27  }
28 }