What is the design model?
In the programming process, we often encounter some typical problems or specific requirements, which were also met by our predecessors, after a lot of Theoretical Summary and practical verification, they have chosen the code structure, programming style, and the way to think about the problem. This is the Design pattern ). The design pattern is like a classical chess set. We use different chess sets to avoid thinking and exploring ourselves.
Single-State (Singleton) Design Mode
Singleton pattern ensures that only one object exists for a class in the entire program. This class cannot create a second object.
Writing of the single-State Design Mode
1. privatize constructors to prevent new objects from being created.
2. Because an object needs to be returned, we need to create an object within the class and remember it using the member variable.
3. Because this class cannot create objects, this member variable cannot be a common member variable and must be static. In this way, a unique object can be created after the class is loaded.
4. We do not want other classes to modify this member variable, so we will private it.
5. A public method is provided to obtain a unique object.
6. Because this method needs to be used without creating an object, it needs to be static.
1/* 2*1. privatize constructors to prevent external objects from being created 3*2. create an object internally and use a member variable to reference the 4 * member variable. This variable can be used externally without creating an object. Therefore, use static modification 5 * only to perform static modification, the value of this variable can still be modified externally. Therefore, 6*7*3 is also private to prevent other classes from modifying this member variable. to allow other class member variables to declare a public method, this object is returned in the method. This method needs to be used without creating an object, so static 8 */9 class SingletonTest {10 // 211 private static SingletonTest singletonTest = new SingletonTest (); 12 // 113 private SingletonTest () {14 15} 16 // 317 public static SingletonTest getInstance () {18 return singletonTest; 19} 20 21}