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
    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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值