2007-12-20

单例模式小结

单例模式可以说是我们在日常开发过程中最常用的模式之一,单于单例模式,也有几种不同的实现版本,我们分别来看:
1.最简单,最原始的单例模式:

public class EagerSingleton{
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton() { }
public static EagerSingleton getInstance()
{
return m_instance;
}
}


2.懒汉式:

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


3.登记式
public class RegSingleton
{
static private HashMap m_registry = new HashMap();
static
{
RegSingleton x = new RegSingleton();
m_registry.put( x.getClass().getName() , x);
}
/**
* 保护的默认构造子
*/
protected RegSingleton() {}
/**
* 静态工厂方法,返还此类惟一的实例
*/
static public RegSingleton getInstance(String name)
{
if (name == null)
{
name = "com.javapatterns.singleton.demos.RegSingleton";
}
if (m_registry.get(name) == null)
{
try
{
m_registry.put( name,
Class.forName(name).newInstance() ) ;
}
catch(Exception e)
{
System.out.println("Error happened.");
}
}
return (RegSingleton) (m_registry.get(name) );
}
/**
* 一个示意性的商业方法
*/
public String about()
{
return "Hello, I am RegSingleton.";
}
}

子类:
public class RegSingletonChild extends RegSingleton
{
public RegSingletonChild() {}
/**
* 静态工厂方法
*/
static public RegSingletonChild getInstance()
{
return (RegSingletonChild)
RegSingleton.getInstance(
"com.javapatterns.singleton.demos.RegSingletonChild" );
}
/**
* 一个示意性的商业方法
*/
public String about()
{
return "Hello, I am RegSingletonChild.";
}
}


4.guice中的单例

public class Singleton {
 static class SingletonHolder {
     static Singleton instance = new Singleton();     
 }     
   public static Singleton getInstance() {     
    return SingletonHolder.instance;     
  }     
 }    
评论
发表评论

提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则

您还没有登录,请登录后发表评论

ecsun
搜索本博客
我的相册
959d6764-20ee-3f5d-8e7d-62b829f243a0-thumb
Faceye基础版(开源)新建标签页
共 24 张
最近加入圈子
存档
最新评论