本文共 2109 字,大约阅读时间需要 7 分钟。
单例模式:一个类只有一个实例方便控制并节约系统资源
优点:节省内存,加快访问速度,因此对象需要被公用的场合适合使用,如多个模块使用同一数据源连接对象等等
缺点:不适用于变化的对象,如果同一类型的对象总是在不同的用例场景发生变化,单例就会引起数据的错误,不能保存彼此的状态
饿汉模式的两种:
public class Singleton_hungry { private final static Singleton_hungry singlen = new Singleton_hungry(); private Singleton_hungry() {} public static Singleton_hungry getInstance() { return singlen; }}class Singleton_hungry2{ private static Singleton_hungry2 instance; static { instance = new Singleton_hungry2(); } private Singleton_hungry2() {} public Singleton_hungry2 getInstance() { return instance; }}
懒汉的六种:
public class Singleton_lazy{ private static Singleton_lazy singleton= null; private Singleton_lazy() { } public static Singleton_lazy getInstance() { if(singleton==null) { singleton = new Singleton_lazy(); } return singleton; }}class Singleton_lazy1{ private static Singleton_lazy1 singleton; private Singleton_lazy1() {} public static synchronized Singleton_lazy1 getInstance() { if (singleton == null) { singleton = new Singleton_lazy1(); } return singleton; }}class Singleton_lazy2{ private static Singleton_lazy2 singleton; private Singleton_lazy2() {} public static Singleton_lazy2 getInstance() { if (singleton == null) { synchronized (Singleton_lazy2.class) { singleton = new Singleton_lazy2(); } } return singleton; }}class Singleton_lazy3{ private static volatile Singleton_lazy3 singleton = null; private Singleton_lazy3() {} private static Singleton_lazy3 getInatance() { if(singleton==null) { synchronized(Singleton_lazy3.class) { if(singleton==null) { singleton = new Singleton_lazy3(); } } } return singleton; }}class Singleton_lazy4{ private Singleton_lazy4() {} private static class SingletonInstance{ private static final Singleton_lazy4 singleton = new Singleton_lazy4(); } public static Singleton_lazy4 getInstance() { return SingletonInstance.singleton; }}class Singleton_lazy5{ public enum singletonInstance{ singleton; public void whatEverMethod() { } }}
转载地址:http://kgeii.baihongyu.com/