`
ican
  • 浏览: 6631 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
最近访客 更多访客>>
社区版块
存档分类
最新评论

设计模式——单例模式

阅读更多

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

饿汉式单例类
代码实例

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

 

懒汉式单例类
代码实例

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;
 }
}

 

登记式单例类

代码实例

import java.util.HashMap;
public class RegSingleton {
 static private HashMap m_registry = new HashMap();
 static
 {
  RegSingleton x = new RegSingleton();
  m_registry.put(x.getClass(), x);
 }
 protected RegSingleton(){}
 static public RegSingleton getInstance(String name)
 {
  if(name == null)
  {
   name = "RegSingleton";
  }
  if(m_registry.get(name) == null)
  {
   try
   {
    m_registry.put(name, Class.forName(name).newInstance());
   }
   catch(Exception e)
   {
    System.out.println("ERRORS hanppened!!");
   }
  }
  return (RegSingleton)m_registry.get(name);
 }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics