The Singleton Pattern is one of the simplest design patterns in Java. This type of design pattern is the creation pattern, which provides the best way to create objects. This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique objects directly, without instantiating the objects of the class.
Application scenario: The singleton mode allows only one object to be created, saving memory and speeding up object access. Therefore, objects need to be used by a common field. For example, multiple modules use the same data source to connect objects. Such as:
- Objects that need to be frequently instantiated and then destroyed.
- An object that takes too much time or resources to create but is often used.
- Stateful tool class objects.
- Objects that frequently access databases or files.
One, hungry
/** * @author GodLiang * @version 1.0 * @date 2021/2/917:12 * @description: Public class HungrySingleton {// Create an object when the class is loaded. Private static HungrySingleton = new HungrySingleton(); Private HungrySingleton() {if (null! = hungrySingleton) throw new RuntimeException(); } public static HungrySingleton getSingletonBean() { return hungrySingleton; }}Copy the code
Advantages and disadvantages of hangry style
Advantages: Without locking, the execution efficiency will be improved.
Disadvantages: Class initialization on load, waste of memory.
Two, slacker style
Double check lock:
/** * @author GodLiang * @version 1.0 * @date 2021/2/9 17:17 * @description: Public class LazySingleton {// Add volatile for visibility. Private volatile static LazySingleton LazySingleton; Private LazySingleton() {// Disable reflection to create objects if (null! = lazySingleton) {throw new RuntimeException(" disallow reflection "); } system.out.println ("c initialization "); } public static LazySingleton getLazySingleton() {} public static LazySingleton getLazySingleton() { If it is not empty, it is already created and does not need to be locked. If (null == synchronized (lazySingleton) {synchronized (lazySingleton) {// synchronize (lazySingleton) { Prevent clogging in lock. If (null == lazySingleton) {lazySingleton = new lazySingleton (); } } } return lazySingleton; } public static void main(String[] args) throws IllegalAccessException, InstantiationException, InterruptedException { for (int i = 0; i < 10; i++) { new Thread(() -> { LazySingleton singletonBean = LazySingleton.getLazySingleton(); }).start(); } LazySingleton.class.newInstance(); }}Copy the code
The advantages and disadvantages
- Advantages: Initialization is performed only on the first call, avoiding memory waste.
- Disadvantages: Locking must be synchronized and volatile to ensure singletons, but locking can affect efficiency.
Other slobs are slightly…