设计模式学习之单例模式

单例模式

单例模式定义:Ensure a class has only one instance , and provide a global point of access to it.(确保一个类只有一个实例,而且自行实例化并且向整个系统提供这个实例。)

单例模式在我们开发中也是常遇到的,一般使用场景如下:

  • 要求生成唯一序列号的环境中
  • 在整个项目中需要共享访问点或共享数据
  • 创建一个对象需要消耗的资源过多
  • 需要定义大量的静态常量和静态方法的环境

单例模式有什么有点呢?如下:

  • 由于单例模式在内存中只有一个实例,减少内存开支,特别是一个对象需要频繁地去创建、销毁时,而且创建或者销毁时性能无法优化,此时单例模式的优势很明显
  • 由于单例模式只生成一个实例,所以减少了系统的性能开销,当一个对象产生需要较多的资源时,如读取配置、产生其他依赖对象时,则可以使用单例模式,让对象永久驻留在内存中。
  • 单例模式可以避免对资源的多重占用,例如一个写文件动作,由于只有一个对象在内存中,避免对同一个资源文件的同时写操作
  • 单例模式可以在系统设置全局访问点,优化和共享资源访问

同样单例模式同样存在缺点

  • 单例模式没有接口,想要扩展很困难
  • 单例模式对测试是不利的
  • 单例模式与单一职责原则有冲突

接下来介绍几个单例模式:

  懒汉模式(第一次使用时才开始实例化):

//懒汉模式 (线程不安全的)
public class Singleton {  
    //设为私有的,防止被外界实例化
    private Singleton() {}  
    private static Singleton singleton=null;   
    public static Singleton getInstance() {  
         if (singleton== null) {    
             singleton= new Singleton();  
         }    
        return singleton;  
    }  
}  

//懒汉模式 (线程安全的)
public class Singleton {  
    //设为私有的,防止被外界实例化
    private Singleton() {}  
    private static Singleton singleton=null;   
    public static synchronized  Singleton getInstance() {  
         if (singleton== null) {    
             singleton= new Singleton();  
         }    
        return singleton;  
    }  
}  

//懒汉模式 (双重校检锁)
public class Singleton {  
    private volatile static Singleton singleton;  
    private Singleton (){}  
    public static Singleton getInstance() {  
    if (singleton == null) {  
        synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton();  
        }  
        }  
    }  
    return singleton;  
    }  
} 

饿汉模式(程序启动时就实例化):

//饿汉模式
public class Singleton {  
    private static Singleton instance = new Singleton();  
    private Singleton (){}  
    public static Singleton getInstance() {  
    return instance;  
    }  
}

静态内部类模式:

//静态内部类模式
public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
} 

 

posted @ 2017-10-20 14:32  随心-HL  阅读(164)  评论(0编辑  收藏  举报