- Scala Functional Programming Patterns
- Atul S. Khot
- 209字
- 2021-07-30 09:44:23
Singletons – being one and only one
A singleton is a class of which only a single instance can exist. How do we prevent anyone from creating yet another instance? The solution is to make the constructor inaccessible. Here it is:
public class Singleton { // Eager initialization private static final Singleton instance = new Singleton(); // 1 private Singleton() { // 2 /* client code cannot create instance */ } // Static factory method public static Singleton getInstance() { // 3 return instance; } // Driver code public static void main(String[] args) { System.out.println(Singleton.getInstance()); System.out.println(Singleton.getInstance()); } }
Dissecting the code:
- At 1, the static initializer creates the instance—also the final keyword ensures that the instance cannot be redefined.
- At 2, the constructor access is private, so only the class methods can access it.
- At 3, the public factory method gives access to the client code.
If you run the Java program, you will see the same object reference printed twice.
A singleton has many forms. There is a null check version and a double-checked locking pattern version. The preceding version is a nicer way—it is the eager-initialized version though.
Note
There is a related pattern called Monostate. Refer to http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf for more on this.
推薦閱讀
- GAE編程指南
- Learning NServiceBus(Second Edition)
- Interactive Data Visualization with Python
- VMware vSphere 6.7虛擬化架構實戰指南
- Processing互動編程藝術
- Internet of Things with the Arduino Yún
- Learning ArcGIS Pro
- 精通Python設計模式(第2版)
- 高級語言程序設計(C語言版):基于計算思維能力培養
- jQuery Mobile移動應用開發實戰(第3版)
- 創意UI Photoshop玩轉移動UI設計
- Clojure Polymorphism
- Mastering Apache Camel
- RESTful Web API Design with Node.js(Second Edition)
- 軟技能2:軟件開發者職業生涯指南