学习自大话设计模式(程杰)
1、单例设计模式:保证内存中对象的唯一性,用于仅需要一个对象的场景
2、单例设计模式实现
2.1:保证对象唯一,即对象不可被外部自由创建,因此将构造函数私有化
2.2:对象不可被外部创建,因此由内部自己创建,再通过外部访问,获取创建的实例,此时函数需要公有静态化
2.3:静态函数需要调用内部创建的实例,因此该实例需要静态化,为避免外部直接访问静态实例,需要将实例私有化。
3、单例模式的两种形式
3.1、饿汉式:类一加载,实例就已经在内存,线程安全
class SingleInstance{
private static SingleInstance single = new SingleInstance();
private SingleInstance(){}
public static getInstance(){
return single;
}
}
3.2、懒汉式:延迟加载,类加载时,实例没有创建在内存,当调用getInstance()时,实例才创建,非线程安全
class SingleInstance{
private static SingleInstance single = null;
private SingleInstance(){}
public static getInstance(){
if(null == single)
single = new SingleInstance();
return single;
}
}
3.3、懒汉式改进版,每次调用都需要实现线程安全,开销大
public class SingletonInstance{
private static SingletonInstance instance = null;
private SingletonInstance(){
}
public static synchronized SingletonInstance getInstance(){
if (null == instance){
instance = new SingletonInstance();
}
return instance;
}
}
3.4、双重检测,当instance为空时,才进入线程安全区,第二个判断是否为空,是因为,当有两个线程同时进入第一个判空,然后其中一个进入与线程安全区,并创建了新的instance,此时如果没有再次判断是否为空,则第二个线程会再次创建实例。
public class SingletonInstance{
private static SingletonInstance instance = null;
private SingletonInstance(){
}
public static SingletonInstance getInstance(){
if (null == instance){
synchronized(SingletonInstance.class){
if(null == instance){
instance = new SingletonInstance();
}
}
}
return instance;
}
}
3.5、使用静态内部类,延迟加载,又保证线程安全
/**
* 单例模式,使用静态内部类,线程安全(推荐)
*/
public class Singleton{
private Singleton(){}
private static class SingletonHolder{
private static Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}