Headfirst java设计模式-单例模式

单例(件)模式:确保一个类只有一个实例,并提供一个全局访问点。

代码实现:
1.懒汉式

/**
 * 通过延迟实例化实现的单例模式
 * 使用synchronized处理多线程访问,但是性能较差。
 *
 */
public class LazyInstantiazeSingleton {
    public static LazyInstantiazeSingleton instance = null;

    private LazyInstantiazeSingleton() {

    }

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

}

2.饿汉式

/**
 * 急切实例化
 * 在jvm加载这个类的时候创建唯一的实例
 * 是线程安全的
 *
 */
public class EagerlySingleton {
    private static EagerlySingleton instance = new EagerlySingleton();

    private EagerlySingleton() {

    }

    public static EagerlySingleton getInstance() {
        return instance;
    }

}

3.双重锁定

/**
 * 通过延迟实例化实现单例模式
 * 双重检查加锁,首先检查实例是否创建,
 * 如果未创建,才进行同步。
 * 这个做法可以大为减少synchronized对性能的影响
 *
 */
public class DoubleCheckSingleton {
    private static volatile DoubleCheckSingleton instance;

    private DoubleCheckSingleton() {

    }

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

    }

}

猜你喜欢

转载自blog.csdn.net/MoonShinesOnMyWay/article/details/81449112