简简单单的singleton

来源:互联网 发布:python能开发前端吗 编辑:程序博客网 时间:2024/04/30 04:46
做Java的singleton时,别忘了处理clone方法哦!

范例 ( 摘自某不知名英文文档 )
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
  }

  private static SingletonObject ref;
}
原创粉丝点击