java设计模式-单例模式

单例模式是最简单但同时也是很重要的一种设计模式,优点有以下几个方面:

1.当内存占用特别大的类需要频繁地创建销毁时,单例模式可以节省内存和提高性能,例如myBatis里面的sessionFactory

2.当需要对文件做单一读写时,例如同一时间只能同时写入一个windows文本文件,则需要用单例来避免多重读写

缺点是:

1.单例模式没有接口,很难对其进行拓展。

2.不利于测试,没办法直接根据接口mock出一个对象出来测试

最后说下其实现方式主要有饿汉模式和懒汉模式。其中懒汉模式又可以细分为几种,后面再说。

饿汉模式代码:public Class Singleton    //在类加载时便实例化自身,饿汉模式

       private static Class Singleton instance = new Singleton();
       private Singleton(){};
       
       public static Singleton getInstance()
    {
return this.instance }
}

懒汉模式且线程安全代码1

public Class Singleton{
       private static Class Singletom instance = null;
       private Singleton(){};
       
       public static Singleton getInstance(){
            if(instance==null){
            //双重检测锁定懒汉模式,如果是直接在getInsance上加锁,因为有99%的情况是线程安全的,会增加性能消耗,故才有双重检测锁定,优化锁,让锁只在1%的情况才执行 
synchronized (Singleton.class) {

if (singleton == null)
{ 
singleton
= new Singleton();
}
}
return this.instance
}
}

懒汉模式且线程安全代码2

public Class Singleton{
      //静态内部类的方式,应该是因为classLoader的机制使得内部类不会在类        
//装载时便实例化,所以可行
private static Class SingletomLoader(){ private static Singleton instance = new Singleton(); } private Singleton(){}; public static final Singleton getInstance(){ return SingletomLoader.instance } }

总结:spring容器中的bean便使用了单例模式,由spring容器控制其bean的生命周期,而如果设置成多例模式的话,则是交由J2EE容器负责其对象的生命周期。

原文地址:https://www.cnblogs.com/sundaymorning/p/7476635.html