- 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.
推薦閱讀
- Oracle從入門到精通(第3版)
- Java EE 6 企業(yè)級(jí)應(yīng)用開發(fā)教程
- Mastering Ember.js
- Learning AWS Lumberyard Game Development
- Building a Quadcopter with Arduino
- Python時(shí)間序列預(yù)測(cè)
- 深入淺出Serverless:技術(shù)原理與應(yīng)用實(shí)踐
- Python算法指南:程序員經(jīng)典算法分析與實(shí)現(xiàn)
- 用戶體驗(yàn)可視化指南
- Cocos2d-x Game Development Blueprints
- R Data Science Essentials
- 遠(yuǎn)方:兩位持續(xù)創(chuàng)業(yè)者的點(diǎn)滴思考
- INSTANT Apache ServiceMix How-to
- Python編程快速上手2
- C語(yǔ)言程序設(shè)計(jì)教程