单例模式

1.懒汉式

//懒汉,线程不安全
public class Singleton1 {
    
    private Singleton1(){}
    
    private static Singleton1 instance=null;
    
    public static Singleton1 newInstance(){
        if(instance==null){
            instance=new Singleton1();
        }
        return instance;
    }

}

 

2.饿汉式

//饿汉式,线程安全
public class Singleton2 {

private Singleton2(){}
    
    private static Singleton2 instance=new Singleton2();
    
    public static Singleton2 newInstance(){
        return instance;
    }
    
}

 

3.懒汉式,线程安全

//懒汉,线程安全,效率不高
public class Singleton3 {

    private Singleton3(){}
    
    private static Singleton3 instance=null;
    
    public static synchronized Singleton3 newInstance(){
        if(instance==null){
            instance=new Singleton3();
        }
        return instance;
    }
}

 

4.使用私有内部类,线程安全

//使用内部私有类按需创建
public class Singleton4 {
    
    private Singleton4(){}
    
    
    private static Singleton4 newInstance(){
        return single.instance;
    }
    
    private static class single{
        private static Singleton4 instance=new Singleton4();
    }

}
posted @ 2016-02-08 17:18  黄大仙爱编程  阅读(79)  评论(0编辑  收藏  举报