Problem solved: Ensure that the object uniqueness of a class in memory.
For example: When multiple programs read a configuration file, it is recommended that the configuration file be encapsulated as an object. It is convenient to manipulate the data, and to ensure that multiple programs read the same profile object, it is necessary that the configuration file object is unique in memory.
Steps:
1 , because the constructor initialization is required for the creation of the object, as long as the constructors in this class are privatized, other programs cannot create the class object again;
2 , you create an object of this class in the class;
3 , define a method that returns the object so that other programs can get the object by means of the method. (Effect: controllable)
The code reflects:
1 , privatization of the constructor;
2 , creating a private and static object of this class;
3 , defines a public and static method that returns the object.
A Hungry Man class Single{private single () {}//privatization constructor. private static Single S = new single (); Creates a private and static object of this class. public static single getinstance () {//defines a publicly-owned and static method that returns the object. return s;}}
A Hungry man no thread safety problem, the disadvantage of a hungry man type is that class one is instantiated and consumes system resources in advance.
Lazy type: Lazy loading mode. Class Single2{private Single2 () {}private static Single2 s = null;public static Single2 getinstance () {if (s==null) s = new Si Ngle2 (); return s;}}
Lazy thread security problem, non-threading security problem, because multiple threads can enter the getinstance () method at the same time, then only need to synchronized the method of the lock synchronization, but this implementation of the operation is very inefficient.
Add a synchronous lock to the method to resolve the thread-safe package org.mlinge.s03; public class Mysingleton { private static Mysingleton instance = null; Private Mysingleton () {} public synchronized static Mysingleton getinstance () { try { if (instance! = null) {/ /lazy }else{ //There may be some preparatory time-consuming work thread.sleep before creating an instance ; Instance = new Mysingleton (); } } catch (Interruptedexception e) { e.printstacktrace (); } return instance; } }
In addition, the custom property created must be static, because the method in the class is called directly using the class name, the method in the class must be static, and the static method cannot access the non-static member variable, so the class-custom instance variable must also be static.
A singleton pattern in Java