单例模式

1、饿汉式单例模式

//饿汉式单例
public class Singleton
{
    private Singleton(){}
    private Singleton uniqueInstance = new Singleton();
    public static Singleton getInstance(){
        return uniqueInstance;
    }
}

2、懒汉式单例模式

//懒汉式单例,延迟实例化
public class Singleton
{
    private Singleton uniqueInstance;
    private Singleton(){}
    public static Singleton getInstance(){
        if(uniqueInstance==null){
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}

3、双重加锁单例模式

//双重加锁,应对多线程
public class Singleton
{
    private volatile static Singelton uniqueInstance;
    private Singleton(){}
    public static Singleton getInstance(){
        if(uniqueInstance==null){
            synchronized (Singleton.class){
                if(uniqueInstance==null){
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

 

posted @ 2018-08-30 15:52  菠菜汤圆  阅读(75)  评论(0编辑  收藏  举报