Design Patterns -- Singleton

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
      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.

个人分类: Design Pattern
下一篇Design Patterns -- Obeserver
想对作者说点什么? 我来说一句

Design Patterns》中文版.pdf

2012年12月07日 10.23MB 下载

Pro Design Patterns in Swift 无水印pdf

2017年09月25日 6.81MB 下载