美文网首页
Singleton Pattern

Singleton Pattern

作者: Wilbur_ | 来源:发表于2020-12-20 12:57 被阅读0次

Singleton

目的: To create one and only one instance of an objects.

Private constructor, static getInstance method like global variable but saves resources (only created when it is needed)

Template:

public  class  Singleton {
  private  static  Singleton  uniqueInstance;
  private  Singleton() {}
  public  static  Singleton  getInstance() {
    if (uniqueInstance  ==  null) {
      uniqueInstance  =  new  Singleton();
    }
    return  uniqueInstance;
  }
}

Example for ChocolateBoiler:


chocolate boiler

Even singleton is implemented in ChocolateBoiler, there still an issue from multithreading

multithreading

1.Simple solution but will effect performance by using synchronized (factor of 100)

  1. Eagerly created instance rather than a lazily created one:

private static Singleton uniqueInstance = new Singleton();

Pro: Avoid multithreading issue

Con: will affect performance if this object never get used

https://dzone.com/articles/always-start-with-eager-initialisation

3.Double checked locking pattern:

volatile 是什么?

variable guaranteeing happens-before relationship

Snip20201217_3.png

https://javarevisited.blogspot.com/2014/05/double-checked-locking-on-singleton-in-java.html#axzz6gtUqmCn3

Use cases of Singleton:

Logging class

System resource monitoring

Registry

ATM https://dzone.com/articles/singleton-design-pattern-%E2%80%93

Summary

  • Private constructor

  • Public static getInstance method

  • The Singleton Pattern also provides a global access point to that instance.

  • Careful about multithreading issue

  • Choose solution based on resource need

Snip20201217_9.png

相关文章

网友评论

      本文标题:Singleton Pattern

      本文链接:https://www.haomeiwen.com/subject/ghjtwktx.html