Design Mode -- Singleton design mode and design mode --
The design pattern is an effective solution to the problem. It is actually an idea.
Singleton design mode:
Solution: ensure that one class can only have one object in the memory. (For example, when multiple programs use the same configuration information object, you must ensure the uniqueness of the object)
How to Ensure uniqueness: 1. Do not allow other programs to use new to create class objects
2. Create an instance of this class in this class
3. provide a method for other programs to obtain the object.
To achieve uniqueness:
1. privatize this type of Constructor (private)
2. Create a class object in this class through new
3. Define a public method to return the created object
Class Single
{
Static Single s = new Single ();
Private Single (){}
Public static Single getInstance ()
{
Return s;
}
}
// The method of calling objects is called by class name. The premise of calling a class name is to call a static method. The content of static access must be static.
Class SingleDemo
{
Single ss1 = Single. getInstance ();
Single ss2 = Single. getInstance ();
System. out. println (ss1 = ss2 );
}
// If the output result is true, the object is unique.
In this way, an object is generated when a class is loaded. It is also known as the tough Singleton mode.
The corresponding lazy format is as follows:
When the class is loaded in, there is no object. The object is created only when the geyInstance method is called. (Delayed Loading Mode)
Class Single2
{
Static Single2 s = null;
Private Single2 (){}
Public static Single2 getInstance ()
{
If (s = null)
S = new Single2 ();
Return s;
}
}
In actual development, there are many hungry Chinese characters, because when the lazy style is used, if a multithreading problem occurs, the uniqueness of the object may cause a security risk. (A lot of interviews are rare)