剑指offer第二版-2.实现单例模式

面试题2:实现单例模式

题目要求:
设计一个类,只能生成该类的一个实例。

/**
 * 单例模式
 * 定义:指实现了特殊模式的类,该类仅能被实例化一次,产生唯一的一个对象
 * 应用举例:windows的任务管理器,回收站,web应用的配置对象,spring中的bean默认也是单例
 * 分类:饿汉式,懒汉式,双检锁,静态内部类,枚举
 * 评价指标有:单例(必须),线程安全,延迟加载,防止反序列化产生新对象,防止反射攻击
 * 实现方法的选择:一般情况下直接使用饿汉式就好了,要求延迟加载时倾向于用静态内部类,涉及到反序列化创建对象或反射问题最好选择枚举
 * 
 * @since 2019年1月24日 下午2:35:36
 * @author xuchao
 *
 */
public class P2_Singleton {

    public static void main(String[] args) {
        // 调用方式
        Singleton1 singleton1 = Singleton1.getInstance();
        Singleton2 singleton2 = Singleton2.getInstance();
        Singleton3 singleton3 = Singleton3.getInstance();
        Singleton4 singleton4 = Singleton4.getInstance();
    }
}

// 版本一:饿汉式
// 特点:线程安全;在类初始化执行到静态属性时就分配了资源,有资源浪费问题;
class Singleton1 {
    // 1.将构造方法私有化,不允许外部直接创建对象
    private Singleton1() {
    }
    // 2.创建类的唯一实例,使用private static修饰
    private static Singleton1 instance = new Singleton1();

    // 3.提供一个用于获取实例的方法,使用public static修饰
    public static Singleton1 getInstance() {
        return instance;
    }
}

// 版本二:懒汉式(非线程安全)
// 特点:在第一次调用获取实例方法时分配内存,实现了懒加载;非线程安全;
class Singleton2 {
    private Singleton2() {
    }

    private static Singleton2 instance;

    public static Singleton2 getInstance() {
        if (instance == null) {
            instance = new Singleton2();
        }
        return instance;
    }
}

// 版本三:懒汉式变种(synchronized同步方法,支持多线程)
// 特点:线程安全;synchronized而造成的阻塞致使效率低,而且很多的阻塞都是没必要的。
class Singleton3 {
    private Singleton3() {
    }

    private static Singleton3 instance;

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

// 版本四:懒汉式变种(synchronized同步块,支持多线程)
// 特点:写法不同,但与版本三有一样的问题
class Singleton4 {
    private Singleton4() {
    }

    private static Singleton4 instance;

    public static Singleton4 getInstance() {

        synchronized (Singleton4.class) {
            if (instance == null) {
                instance = new Singleton4();
            }
        }
        return instance;
    }
}

 

posted @ 2019-01-29 15:37  思丿无邪  阅读(141)  评论(0编辑  收藏  举报