单例模式的要点:
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);
- }
- }