什么是单例模式?单例模式有哪些?单例模式怎么写?

来源:互联网 发布:手机间谍软件官方网站 编辑:程序博客网 时间:2024/04/30 11:58

单例模式

什么是单例模式?

单例模式是一种常用的软件设计模式。
在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。即一个类只有一个对象实例

个人理解:单例模式就是同事new多个一样的对象出来。new的都是同一个。

单例模式有哪几种?

就种数来说常用的有两种:懒汉模式和饿汉模式。
但是写法却有许多种。

主要常用的:懒汉模式和饿汉模式。

不能用于多线程

//懒汉模式不安全public class Dog {    private static Dog dog;    private Dog(){    }    public  static Dog newInstance(){        if(dog == null){            dog = new Dog();        }        return dog;    }}

安全版的懒汉模式,能用于多线程,但是效率很低。
利用锁旗标锁起来。代码如下:

public class Dog {      private static Dog dog ;      private Dog (){}      public static synchronized Dog newInstance() {      if (dog == null) {          dog = new Dog ();      }      return dog ;      }  }  

饿汉模式,代码如下:

public class Cat {    private static Cat cat = new Cat();    private Cat(){    }    public static Cat newInstance(){        return cat;    }}

下面是其余几种:转载自http://cantellow.iteye.com/blog/838473

静态内部类,代码如下:

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

这种方式同样利用了classloder的机制来保证初始化instance时只有一个线程,它跟第三种和第四种方式不同的是(很细微的差别):第三种和第四种方式是只要Singleton类被装载了,那么instance就会被实例化(没有达到lazy loading效果),而这种方式是Singleton类被装载了,instance不一定被初始化。因为SingletonHolder类没有被主动使用,只有显示通过调用getInstance方法时,才会显示装载SingletonHolder类,从而实例化instance。想象一下,如果实例化instance很消耗资源,我想让他延迟加载,另外一方面,我不希望在Singleton类加载时就实例化,因为我不能确保Singleton类还可能在其他的地方被主动使用从而被加载,那么这个时候实例化instance显然是不合适的。这个时候,这种方式相比第三和第四种方式就显得很合理。

枚举,代码如下:

public enum Singleton {      INSTANCE;      public void whateverMethod() {      }  }  

这种方式是Effective Java作者Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,可谓是很坚强的壁垒啊,不过,个人认为由于1.5中才加入enum特性,用这种方式写不免让人感觉生疏,在实际工作中,我也很少看见有人这么写过。

双重校验锁,代码如下:

public class Singleton {      private volatile static Singleton singleton;      private Singleton (){}      public static Singleton getSingleton() {      if (singleton == null) {          synchronized (Singleton.class) {          if (singleton == null) {              singleton = new Singleton();          }          }      }      return singleton;      }  }  
原创粉丝点击