关闭

Design Patterns -- Singleton

691人阅读 评论(0) 收藏 举报

1. The intent of the Singleton is to ensure that a class has only one instance and to provide a global point of access to it.

2. A singleton is usually lazy-initialized. [lazy-initialized is like:if( filed == null) { // initial }  return field; ]

3. Symchronize is important in lazy-initialize when initial Singleton (multi-thread).( see book: Concurrent Programming in Java )

4. See the source code of java.util.Collections.SingletonSet

5. UML diagram of Singleton,   see pic:

 

6. To use Singleton, approaches are below:

6.1 use static function to create instance(and make the constractor private so that other can not use it),like:

public class Singleton {
            private static Singleton s;
            private Singleton(){};
        
        // lazy-initialize         
        public static Singleton getInstance() {
         if (s == null)
            s = new Singleton();
          return s;
        }
}

6.2 Use static field to mark whether the single instance has been created, like:

class Singleton {
  static boolean instance_flag = false; // true if 1 instance
  public Singleton() {
    if (instance_flag)
      throw new SingletonException("Only one instance allowed"); //custom exception
    else
      instance_flag = true; // set flag for 1 instance
  }
}

6.3 use Collection: repeat object is not allowed in some collections, can be extended to a specified number of instance of a class.

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:219915次
    • 积分:3635
    • 等级:
    • 排名:第8972名
    • 原创:132篇
    • 转载:19篇
    • 译文:1篇
    • 评论:22条
    文章分类
    最新评论
    其他