做Java的singleton时,别忘了处理clone方法哦!
范例 ( 摘自某不知名英文文档 )
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}
范例 ( 摘自某不知名英文文档 )
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
}
博客给出了Java代码,包含获取单例对象的方法,当引用为null时创建单例对象并返回;还给出了克隆方法,通过抛出异常禁止克隆操作,体现了单例模式的特性。

被折叠的 条评论
为什么被折叠?



