- 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.
推薦閱讀
- SQL Server 從入門到項(xiàng)目實(shí)踐(超值版)
- Flask Blueprints
- Python數(shù)據(jù)分析入門與實(shí)戰(zhàn)
- OpenCV實(shí)例精解
- Java EE框架整合開發(fā)入門到實(shí)戰(zhàn):Spring+Spring MVC+MyBatis(微課版)
- 零基礎(chǔ)學(xué)MQL:基于EA的自動(dòng)化交易編程
- Mastering Python High Performance
- Spring Boot進(jìn)階:原理、實(shí)戰(zhàn)與面試題分析
- Visual FoxPro程序設(shè)計(jì)
- Mastering Android Studio 3
- Mastering Apache Camel
- Web前端開發(fā)技術(shù):HTML、CSS、JavaScript
- Less Web Development Cookbook
- C語(yǔ)言程序設(shè)計(jì)
- Scratch編程入門與算法進(jìn)階(第2版)