设计模式:单例

来源:互联网 发布:德国电子地图软件 编辑:程序博客网 时间:2024/04/28 21:13

个人认为java中的各种常用设计模式很重要,所以把一些自己理解的东西写下来。

单例模式主要作用是保证在Java应用程序中,一个类Class只有一个实例在。 使用单例模式的好处还在于可以节省内存,因为它限制了实例的个数,有利于Java垃圾回收。

主要分两种:

1.饿汉式

方案1:

class Singleton {  private static Singleton instance=new Singleton();  private Singleton(){}  static Singleton getInstance() {      return instance;  }}

方案1中创建instance对象时无法传入参数,所以应用有限。

方案2:

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

方案2解决了方案1的缺陷。

2.懒汉式

方案1:

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


方案1中如果两个线程并发调用,假设线程一先判断完instance是否为null,然后准备执行new Singleton()。此刻线程二进入到判断instance是否为null,由于线程一还没执行nenew Singleton()方法,所以instance仍然是空的,因此线程二执行了new Signleton操作,就会出现了两个instance对象。

方案2:

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

方案2解决了方案1中的同步问题。

其中方案1是网上搜到的面试题的答案,方案2是自己的一些理解。

 

 


 

原创粉丝点击