单例模式

来源:互联网 发布:电脑桌面壁纸设计软件 编辑:程序博客网 时间:2024/06/06 22:11

由于排版可能会影响代码查看,请移步我的博客单例模式

一、什么是单例模式

1、单例:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

2、单例模式是一种常用的软件设计模式之一,其目的是保证整个应用中只存在类的唯一个实例。

比如我们在系统启动时,需要加载一些公共的配置信息,对整个应用程序的整个生命周期中都可见且唯一,这时需要设计成单例模式。如:spring容器,session工厂,缓存,数据库连接池,网络连接池等等。

二、如何保证实例的唯一

1、防止外部初始化

2、由类本身进行实例化

3、保证实例化一次

4、对外提供获取实例的方法

5、线程安全

三、几种单利模式的实现和比较

1、饿汉模式

“因为饿,所以要立即吃饭,刻不容缓”,在定义类的静态私有变量同时进行实例化。

    public class Singleton {        private static final Singleton singleton = new Singleton();        private Singleton() {        }        public static Singleton getInstance() {            if (instance == null) {                  instance = new Singleton();             }            return instance;          }    }

当然上面的饿汉模式中的对象,你也可以放在静态代码块中进行初始化

    public class Singleton {        private static  Singleton singleton = null;        static{            singleton = new Singleton()        }        private Singleton() {        }        public static Singleton getInstance() {            return singleton;        }    }

2、懒汉模式

“因为懒,所以都忘记了创建初始对象”,在定义类的静态私有变量,不进行初始化。
“`java
public class Singleton {

    private static Singleton instance;    private Singleton (){}    public static Singleton getInstance() {          if (instance == null) {              instance = new Singleton();         }        return instance;      }  }  
3、如果使涉及到线程问题,上面的例子并不能满足您的要求了,因为线程不安全,那如何实现线程安全的单例模式呢,上代码(懒汉) ```java     public class Singleton {        private static Singleton instance;        private Singleton (){}        public static  Singleton getInstance() {              if (singleton == null) {   //  1号                synchronized (Singleton.class) {                    if (singleton == null) {  //2号                        singleton = new Singleton();                    }                }            }            return singleton;        }      }  

可能您会疑惑,为什么要判断两次空?举个例子,现在有两个线程A和B。假设A先执行,B后执行,此时同时运行到1号备注,此时的singleton == null。下一刻A继续运行,B等待,当A执行完成后singleton != null。所以当B执行的时候不需要再创建。所以需要两次判断。

4、静态内部类。优点:既避免了同步带来的性能损耗,又能够延迟加载

public class Singleton {    private Singleton() {    }    private static class SingletonHolder {        private static final Singleton singleton = new Singleton();    }    public static Singleton getInstance() {        return SingletonHolder.singleton;    }}

5、枚举。天然线程安全,可防止反射生成实例。

public enum Singleton {    INSTANCE;    public void init() {        System.out.println("资源初始化。。。");    }}

四、总结

优点:该类只存在一个实例,节省系统资源;对于需要频繁创建销毁的对象,使用单例模式可以提高系统性能。

缺点:不能外部实例化(new),调用人员不清楚调用哪个方法获取实例时会感到迷惑,尤其当看不到源代码时。

附录:后续将会推出一系列设计模式文章,请关注我的博客 lueans,希望能帮助到大家

0 0
原创粉丝点击