单例模式

1.饿汉模式

构造函数私有,静态常量(实例化),公有静态方法来获取实例。

public class Singleton {

    private final static Singleton INSTANCE = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return INSTANCE;
    }
}

2.懒汉模式

构造函数私有,静态变量,公有静态方法来获取实例(先判断变量是否为null)。

public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

饿汉模式是非线程安全的,所以需要加同步关键字synchronized 来变成同步方法

3.双重检查(推荐)

public class Singleton {

    private static volatile Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

4.静态内部类(推荐)

public class Singleton {

    private Singleton() {}

    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

 

posted @ 2018-09-07 09:33  水墨江南110  阅读(137)  评论(0)    收藏  举报