设计模式(八)之单例模式

线程安全写法:

public class Singleton {

    /* 线程安全推荐写法 */
    private Singleton() {
    }

    static class SigletonHandler {
        static Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return SigletonHandler.instance;
    }

    /* 线程安全双check写法 */
    private static Singleton instance;

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

    /* 线程安全 饿汉写法 */
    private static Singleton instance2 = new Singleton();

    public static Singleton getInstance3() {
        return instance2;
    }
}

平时用到的单例代理类:

public abstract class Lazy<T> implements AutoCloseable {
    private volatile T instance = null;
    protected abstract T makeObject();
    protected abstract void destroyObject(T obj);

    public T get() {
        if (instance == null) {
            synchronized (this) {
                if (instance == null) {
                    instance = makeObject();
                }
            }
        }
        return instance;
    }

    @Override
    public void close() {
        synchronized (this) {
            if (instance != null) {
                T instance_ = instance;
                instance = null;
                destroyObject(instance_);
            }
        }
    }
}

调用代理类:

public class Consumer {

    public static void main(String[] args) {
        Lazy<MyClass> lazy = new Lazy<MyClass>() {
            @Override
            protected MyClass makeObject() {

                return new MyClass(5);
            }

            @Override
            protected void destroyObject(MyClass obj) {
                obj.index = 0;
            }
        };

        MyClass myClass = lazy.makeObject();
    }
}
上一篇:设计模式(五)之工厂方法模式


下一篇:Java中的==和equals区别