[Java design mode] java Singleton mode and java Design Mode
What is the singleton mode:
The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system. In computer systems, driver objects of thread pools, caches, log objects, dialogs, printers, and graphics cards are often designed as Singleton. These applications have more or less resource manager functions. Each computer can have several printers, but only one Printer Spooler can be used to prevent two print jobs from being output to the Printer at the same time. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being simultaneously called by both requests. In short, the singleton mode is selected to avoid inconsistency and avoid multiple leaders. Why do I need to use the singleton mode? For example, the configuration file reading class, when a java program is running on the service, it needs to use parameters in the configuration file at intervals, you can't keep a new object in the program every time. The best way is to create an object when starting the program, and keep using the attribute values in the object. This requires the singleton design mode. Example: 1. Lazy Singleton
public class Singleton { private static class LazyHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return LazyHolder.INSTANCE; } }
Ii. Hunger-type Singleton class // hunger-type Singleton class. It has been self-instantiated during class initialization.
Public class Singleton1 {private Singleton1 () {} private static final Singleton1 single = new Singleton1 (); // static factory method public static Singleton1 getInstance () {return single ;}}