avatar

目录
Design Patterns : Singleton

What is Singleton pattern

[Wikipedia]: https://en.wikipedia.org/wiki/Singleton_pattern: In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system.

image-20200318181121966

Characteristic

  • only 1 instance create
  • Guarantees controlled of a resource
  • Lazily Loaded

Example of use

  • Java Runtime (object)
  • Logger
  • Spring Beans

Code Example

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class DbSingleton {
private static DbSingleton instance = null;

/*
*make it as private ensure constructor can't be called via outer class
*/
private DbSingleton(){
if( instance != null){
throw new RuntimeException("Use getInstance() method to create instance");
}
}

public static DbSingleton getInstance(){
if(instance == null){ // lazy loading, it won't be created when system is starting up
synchronized (DbSingleton.class){ // thread safe
if(instance == null) {
instance = new DbSingleton();
}
}
}
return instance;
}
}

Pitfalls

  1. Often overused, this could cause performance isue if make everything as singleton
  2. Difficult to unit test, as construstors and members are private
  3. If not carefull, the are not thread-safe. From above, we have added ensured thread safe
  4. Sometimes confuse for Factory: when people start making the getInstance method, as soon as it needs paramerters, it is not a singleton anymore but rather a factory.
  5. java.util.Calendar is NOT a singleton. It actually more of a prototype pattern. As you are getting a new unique instance each time you call getInstance method.
文章作者: Aries Kou
文章链接: http://yoursite.com/posts/Design-Patterns/1349066953.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Aries' Blog
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论