`
litxuf
  • 浏览: 119369 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

设计模式——单例模式

    博客分类:
  • java
阅读更多

单例模式的要点:
1、某个类只能有一个实例;
2、必须自行创建自己的唯一实例;
3、必须自行给所有其他对象提供这一实例。

饿汉式单例类
代码实例

Java代码

 

public class EagerSingleton {
 private static final EagerSingleton m_instance = new EagerSingleton(); 
 /**
  * 私有的默认构造函数
  */
 private EagerSingleton(){}
 /**
  * 静态工厂方法
  * @return
  */
 public EagerSingleton getInstance()
 {
  return m_instance;
 }
}

 

懒汉式单例类
代码实例

Java代码 复制代码
public class LazySingleton {
 private static LazySingleton m_instance = null;
 private LazySingleton(){}
 synchronized public static LazySingleton getInstance()
 {
  if(m_instance == null)
  {
   m_instance = new LazySingleton();
  }
  return m_instance;
 }
}

 

登记式单例类

代码实例

Java代码 复制代码
  1. import java.util.HashMap;   
  2. public class RegSingleton {   
  3.  static private HashMap m_registry = new HashMap();   
  4.  static  
  5.  {   
  6.   RegSingleton x = new RegSingleton();   
  7.   m_registry.put(x.getClass(), x);   
  8.  }   
  9.  protected RegSingleton(){}   
  10.  static public RegSingleton getInstance(String name)   
  11.  {   
  12.   if(name == null)   
  13.   {   
  14.    name = "RegSingleton";   
  15.   }   
  16.   if(m_registry.get(name) == null)   
  17.   {   
  18.    try  
  19.    {   
  20.     m_registry.put(name, Class.forName(name).newInstance());   
  21.    }   
  22.    catch(Exception e)   
  23.    {   
  24.     System.out.println("ERRORS hanppened!!");   
  25.    }   
  26.   }   
  27.   return (RegSingleton)m_registry.get(name);   
  28.  }   
  29. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics