javaSE基础18之设计模式

1,单例模式

java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在

饿汉式  懒汉式


public class Singleton1 {
    //构造方法私有
    private Singleton1(){
        
    }
    //饿汉单例实现
    private static final Singleton1 single=new Singleton1();
    //静态工厂
    public static Singleton1 getInstance(){
        return single;
    }
    

}

》》》》》》》》》》》

public class Singleton2 {
   //构造方法私有
    private Singleton2(){
    }
    
    //懒汉式单例实现
    private static Singleton2 single;
    
    //工厂
    public static synchronized Singleton2 getInstance(){
        if(single==null){
            System.out.println("第一次实例化时调用");
            single=new Singleton2();
        }
        return single;
    }

}

》》》》》》》》》》》》

public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Singleton1 single=new Singleton1();
        Singleton1 single1= Singleton1.getInstance();
        Singleton1 single2= Singleton1.getInstance();
        System.out.println("饿汉式:"+(single1==single2));
        
        Test t=new Test();
        Test t2=new Test();
        System.out.println(t==t2);
        
         Singleton2 single3= Singleton2.getInstance();
        Singleton2 single4= Singleton2.getInstance();
        System.out.println("饿汉式:"+(single3==single4));
        
    }
    
}



你可能感兴趣的:(java基础)