1.单例设计模式

清华大学马士兵老师亲授-- 23种Java设计模式详解 P2 

 
知识点:
  
 
1.饿汉式
/**
 * Describe:恶汉式
 * 类加载到内存后,就实例化一个单例,【JVM保证线程安全】
 * 有点:简单实用
 * 缺点:不管你用不用,类装载时就完成实例化
 * (只有在用的时候才会去加载,所以这个缺点也不算缺点...)
 */
public class Singleton01 {
    private static final Singleton01 INSTANCE = new Singleton01();

    //设置为外部不能调用
    private Singleton01() {
    }

    public static Singleton01 getInstance() {
        return INSTANCE;
    }
}
/**
 * Describe:恶汉式
 * 跟01一个意思
 */
public class Singleton02 {
    private static final Singleton02 INSTANCE;

    static {
        INSTANCE = new Singleton02();
    }

    //设置为外部不能调用
    private Singleton02() {
    }

    public static Singleton02 getInstance() {
        return INSTANCE;
    }
}
2.懒汉式
/**
 * Describe:lazy loading 懒汉式
 * 【线程不安全】
 */
public class Singleton03 {
    private static Singleton03 INSTANCE;

    //设置为外部不能调用
    private Singleton03() {
    }

    public static Singleton03 getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton03();
        }

        return INSTANCE;
    }
}
/**
 * Describe:lazy loading 03-->04 加锁 懒汉式
 *
 * <p>
 * 加锁解决线程不安全 类被锁住了
 * 导致效率下降
 */
public class Singleton04 {
    private static Singleton04 INSTANCE;

    //设置为外部不能调用
    private Singleton04() {
    }

    public static synchronized Singleton04 getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton04();
        }

        return INSTANCE;
    }

}
/**
 * Describe:lazy loading 04-->05 加锁 懒汉式
 * 线程不安全
 */
public class Singleton05 {
    private static Singleton05 INSTANCE;

    //设置为外部不能调用
    private Singleton05() {
    }
    public static Singleton05 getInstance() {

        if (INSTANCE == null) {
            //妄图通过减小同步代码块的方式提高效率,然而不可行,依然线程不安全
            synchronized (Singleton05.class) {
                INSTANCE = new Singleton05();
            }

        }

        return INSTANCE;
    }

}
/**
 * Describe:lazy loading  懒汉式
 * 【双重检查】
 * 【线程安全】
 */
public class Singleton06 {
    private static volatile Singleton06 INSTANCE;

    //设置为外部不能调用
    private Singleton06() {
    }

    public static Singleton06 getInstance() {

        if (INSTANCE == null) {
            synchronized (Singleton06.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Singleton06();
                }
            }
        }

        return INSTANCE;
    }
}

3.静态内部类
/**
 * Describe:静态内部类方式  【完美】
 * 【Jvm保证单例】
 * 【线程安全】
 * 【懒加载】加载外部类时不会加载内部类
 */
public class Singleton07 {

    //设置为外部不能调用
    private Singleton07() {
    }

    public static Singleton07 getInstance() {
        return Singleton07Holder.INSTANCE;
    }

    private static class Singleton07Holder {
        private final static Singleton07 INSTANCE = new Singleton07();
    }
}
4.枚举单例
/**
 * Describe:枚举单例  【完美中的完美】
 * 【线程安全】
 * 【防止反序列化】
 */
public enum Singleton08 {
    INSTANCE;

    public void m() {
    }
}
总结:【饿汉式01】最实用, 【枚举】最完美,但是枚举看起来别扭





posted @ 2020-12-23 11:20  Nixon  阅读(104)  评论(0编辑  收藏  举报