单例模式

懒汉式

静态工厂方法,线程不安全,推荐评级:★

public class Singleton {

    private static Singleton singleton = null;

    //构造方法private避免了类在外部被实例化
    private Singleton() {
    }

    //静态工厂方法
    public static Singleton getInstance(){
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }

}

线程安全,加锁synchronized,加锁会影响效率,推荐评级:★★

public class Singleton {

    private static Singleton singleton = null;

    //构造方法private避免了类在外部被实例化
    private Singleton() {
    }

    //加同步synchronized
    public static synchronized Singleton getSynInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }

}

饿汉式

线程安全,实际使用较多,推荐评级:★★★★★

public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton (){}
    public static Singleton getInstance() {
    return instance;
    }
}

双重检查锁定

线程安全,推荐评级:★★★★

public class Singleton {

    private static Singleton singleton = null;

    //构造方法private避免了类在外部被实例化
    private Singleton() {
    }

    //双重检查锁定
    public static Singleton getDoubleCheckInstance(){
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

}

静态内部类

线程安全,推荐评级:★★★★★

public class Singleton {

    private static Singleton singleton = null;

    //构造方法private避免了类在外部被实例化
    private Singleton() {
    }

    //★(推荐)静态内部类(既实现了线程安全,又避免了同步带来的性能影响)
    private static class LazyHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    public static final Singleton getInnerSingleton(){
        return LazyHolder.INSTANCE;
    }

}

枚举

线程安全,推荐评级:★★★

public enum Singleton {
     INSTANCE;
     public void doSomeThing() {
     }
 }

发表评论

邮箱地址不会被公开。 必填项已用*标注