单例模式

*单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。两个实现方案,饿汉式、懒汉式,类图如下:

*饿汉式是典型的空间换时间,装载类的时候就创建实例然后每次调用的时候就不需要做判断,这就节省了系统的运行时间。

 1 //饿汉式
 2 public class EagerSingleton{
 3     private static final EagerSingleton instance = new EagerSingleton();
 4     private EagerSingleton(){
 5         throw new Exception();//防止反射暴力破解
 6     }
 7     public static EagerSingleton getInstance(){        
 8         return instance;
 9     }
10 }

*懒汉式的实现体现了缓存思想,当资源或数据被频繁使用而这些资源或数据储存在软件系统之外(比如数据库、硬盘、网络等),这是会影响系统性能。这时需要把这些数据缓存到内存之中,每次操作先到内存中搜索,如果没有再去获取,并设置到缓存之中。这是一种典型的时间换空间的方案。

 1 //懒汉式 双重加锁**jdk1.5以后的版本适用
 2 public class LazySingleton{
 3     private volatile static LazySingleton instance = null;
 4     private LazySingleton(){
 5         throw new Exception();//防止反射暴力破解
 6     }
 7     //懒汉式线程不安全
 8     public static LazySingleton getInstance(){
 9         if(instance==null){
10             synchronized (LazySingleton.class) {
11                 instance = new LazySingleton();
12             }
13         }
14         return instance;
15     }
16 }

线程同步机制会影响系统效率,这里有个优化版本:

 1 //懒汉式的改进 使用静态内部类
 2 public class LazySingleton{
 3     //调用getInstance()时会初始化LazySingletonHolder的静态域,这里不需要考虑同步问题
 4     private static class LazySingletonHolder{
 5         private static LazySingleton instance = new LazySingleton();
 6     }
 7     private LazySingleton(){
 8         throw new Exception();//防止反射暴力破解
 9     }
10     public static LazySingleton getInstance(){
11         return LazySingletonHolder.instance;
12     }
13 }

*总结:单例模式的本质是控制实例数目。

 

posted @ 2017-06-10 13:10  夏虫语冰、  阅读(138)  评论(0编辑  收藏  举报