设计模式三 之 单例模式(Singleton)

单例模式(Singletonhtml

单例对象能保证在一个JVM中,该对象只有一个实例存在。java

写法一:可是有可能会出现线程安全问题安全

public class Singleton {  
  
    /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */  
    private static Singleton instance = null;  
  
    /* 私有构造方法,防止被实例化 */  
    private Singleton() {  
    }  
  
    /* 静态工程方法,建立实例 */  
    public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
  
    /* 若是该对象被用于序列化,能够保证对象在序列化先后保持一致 */  
    public Object readResolve() {  
        return instance;  
    }  
}

写法二:考虑到线程安全问题服务器

public class SingletonTest {  
  
    private static SingletonTest instance = null;  
  
    private SingletonTest() {  
    }  
  
    private static synchronized void syncInit() {  
        if (instance == null) {  
            instance = new SingletonTest();  
        }  
    }  
  
    public static SingletonTest getInstance() {  
        if (instance == null) {  
            syncInit();  
        }  
        return instance;  
    }  
}

 

省去了new操做符,下降了系统内存的使用频率,减轻GC压力。线程

有些类如交易所的核心交易引擎,控制着交易流程,若是该类能够建立多个的话,系统彻底乱了。(好比一个军队出现了多个司令员同时指挥,确定会乱成一团),因此只有使用单例模式,才能保证核心交易服务器独立控制整个流程。code

Reference:https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.htmlhtm

相关文章
相关标签/搜索