- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 284字
- 2021-06-25 20:52:31
Singleton pattern
The singleton pattern is probably the most widely used design pattern since the inception of Java. It is a simple pattern, easy to understand and to use. Sometimes it is used in excess, and in scenarios where it is not required. In such cases, the disadvantages of using it outweigh the advantages it brings. For this reason, the singleton is sometimes considered an anti-pattern. However, there are many scenarios where singletons are necessary.
As its name suggests, the singleton pattern is used to ensure that only a single instance of an object can be created. In addition to that, it also provides global access to that instance. The implementation of a singleton pattern is described in the following class diagram:

The implementation of the singleton pattern is very simple and consists of a single class. To ensure that the singleton instance is unique, all singleton constructors should be made private. Global access is done through a static method that can be globally accessed to get the singleton instance, as shown in the following code:
public class Singleton
{
private static Singleton instance;
private Singleton()
{
System.out.println("Singleton is Instantiated.");
}
public static Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}
public void doSomething()
{
System.out.println("Something is Done.");
}
}
When we need to use the singleton object somewhere in our code, we simply invoke it like this:
Singleton.getInstance().doSomething();
In the getInstance method, we check whether the instance is null. If the instance is not null, it means the object was created before; otherwise, we create it using the new operator. After that, in either case, it is not null anymore, so we can return the instance object.
- 數(shù)據(jù)科學實戰(zhàn)手冊(R+Python)
- DB2 V9權(quán)威指南
- Mastering Ext JS(Second Edition)
- Visual FoxPro程序設(shè)計教程(第3版)
- Windows系統(tǒng)管理與服務配置
- Practical Data Science Cookbook(Second Edition)
- iOS應用逆向工程(第2版)
- SQL基礎(chǔ)教程(視頻教學版)
- Visual FoxPro程序設(shè)計
- Procedural Content Generation for C++ Game Development
- Instant PHP Web Scraping
- JavaScript腳本特效編程給力起飛
- 深度探索Go語言:對象模型與runtime的原理特性及應用
- 區(qū)塊鏈項目開發(fā)指南
- Java高手是怎樣煉成的:原理、方法與實踐