- Spring 5 Design Patterns
- Dinesh Rajput
- 254字
- 2021-07-08 09:59:33
Sample implementation of the Singleton design pattern
In the following code example, I will be creating a class with a method to create an instance of this class if one does not exist. If the instance is already present, then it will simply return the reference of that object. I have also taken thread safety into consideration, and so I have used a synchronized block here before creating the object of that class.
Let's check out the UML diagram for the Singleton design pattern:
package com.packt.patterninspring.chapter2.singleton.pattern; public class SingletonClass { private static SingletonClass instance = null; private SingletonClass() { } public static SingletonClass getInstance() { if (instance == null) { synchronized(SingletonClass.class){ if (instance == null) { instance = new SingletonClass(); } } } return instance; } } }
One thing to be noted in the preceding code is that I have written a private constructor of the SingletonClass class to make sure that there is no way to create the object of that class. This example is based on lazy initialization, which means that the program creates an instance on demand the first time. So you could also eagerly instantiate the object to improve the runtime performance of your application. Let's see the same SingletonClass with eager initialization:
package com.packt.patterninspring.chapter2.singleton.pattern; public class SingletonClass { private static final SingletonClass INSTANCE =
new SingletonClass(); private SingletonClass() {} public static SingletonClass getInstance() { return INSTANCE; } }
Now that we've seen the singleton design pattern, let's turn to a different variant of it--the Prototype design pattern.
- JavaScript前端開發模塊化教程
- PyTorch自動駕駛視覺感知算法實戰
- 從0到1:HTML+CSS快速上手
- Python神經網絡項目實戰
- Java Web基礎與實例教程
- 鋒利的SQL(第2版)
- Getting Started with Python Data Analysis
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- AIRIOT物聯網平臺開發框架應用與實戰
- C++從入門到精通(第5版)
- Mastering Xamarin.Forms(Second Edition)
- Service Mesh實戰:基于Linkerd和Kubernetes的微服務實踐
- 寫給大家看的Midjourney設計書
- 青少年學Python(第2冊)
- Greenplum構建實時數據倉庫實踐