您的位置:首页 > 其它

收集了部分关于Singleton的资料

2009-05-15 17:09 387 查看
收集了部分Singletong Pattern的文章。突然发觉原来Singleton模式还没那么简单啊。

感觉比较好的实现有

1.volatile 关键字的使用

Double-checked synchronization,将instance声明为volatile即可,在jdk5以上版本。

// Works with acquire/release semantics for volatile
// Broken under current semantics for volatile
class Foo {
private volatile Helper helper = null;
public Helper getHelper(); {
if (helper == null); {
synchronized(this); {
if (helper == null);
helper = new Helper();;
}
}
return helper;
}
}

// Works with acquire/release semantics for volatile
// Broken under current semantics for volatile
class Foo {
private volatile Helper helper = null;
public Helper getHelper(); {
if (helper == null); {
synchronized(this); {
if (helper == null);
helper = new Helper();;
}
}
return helper;
}
}


2.一种比较好的实现方式是Initialization on Demand Holder (IODH):

public   class  Singleton  {
static  class  SingletonHolder  {
static  Singleton instance  =   new  Singleton();
}

public   static  Singleton getInstance()  {
return  SingletonHolder.instance;
}
}


3. 在effective java里的一种新型的singleton:

// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

参考资料:

http://www.jdon.com/jivejdon/thread/17133.html

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

http://www.javaeye.com/topic/363729

http://www.chinaunix.net/jh/4/713279.html

http://www.javaeye.com/topic/13894

http://www.javaeye.com/topic/211471?page=1

http://www.javaeye.com/topic/211937

http://www.blogjava.net/samyang/archive/2007/12/21/169310.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: