单例设计模式

一、UML

Singleton.png

二、基本步骤

1、私有化构造方法
2、通过一个静态方法或者枚举返回单例对象
3、多线程时保证线程安全
4、确保单例类对象序列化时不会重新构建对象

三、实现方式

1、饿汉式
代码
/**
 * @author lizihanglove
 * @email [email protected]
 * @date 2018-01-02
 * @time 13:02
 * @desc 恶汉式单例模式
 */

public class HungrySinglton {
    private static HungrySinglton instance = new HungrySinglton(); 
    private HungrySinglton() {
    }
    
    public static HungrySinglton getInstance(){
        return instance;
    }
}
2、懒汉式
代码
/**
 * @author lizihanglove
 * @email [email protected]
 * @date 2018-01-02
 * @time 13:06
 * @desc 懒汉式单例
 */

public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {
    }

    private static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

3、双重校验锁式
代码
**
 * @author lizihanglove
 * @email [email protected]
 * @date 2018-01-02
 * @time 13:10
 * @desc 双重校验锁单例
 */

public class DoubleCheckLockSingleton {
    private static DoubleCheckLockSingleton instance;

    private DoubleCheckLockSingleton() {
    }

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

4、静态内部类式
代码
/**
 * @author lizihanglove
 * @email [email protected]
 * @date 2018-01-02
 * @time 13:14
 * @desc 静态内部类单例
 */

public class StaticInnerClassSingleton {
    
    private StaticInnerClassSingleton() {
    }
    
    public static StaticInnerClassSingleton getInstance(){
        return SingletonHolder.instance;
    }
    
    private static class SingletonHolder{
        private static final StaticInnerClassSingleton instance= new StaticInnerClassSingleton();
    }
}
5、枚举式
代码
/**
 * @author lizihanglove
 * @email [email protected]
 * @date 2018-01-02
 * @time 13:18
 * @desc 枚举单列
 */

public enum  EnumSingleton {
    INSTANCE;
    public void doSomething(){
        //do something
    }
}
6、容器式
代码

/**
 * @author lizihanglove
 * @email [email protected]
 * @date 2018-01-02
 * @time 13:22
 * @desc 容器式单例,可忽略
 */

public class ContainerSingleton {
    private static Map objectMap = new HashMap();

    private ContainerSingleton() {
    }

    public static void registerInstance(String key, Object value) {
        if (!objectMap.containsKey(key)) {
            objectMap.put(key, value);
        }
    }

    public static ContainerSingleton getInstance(String key) {
        return (ContainerSingleton) objectMap.get(key);
    }

另:在Android中常用双重校验锁式单例。

你可能感兴趣的:(单例设计模式)