First, when to use the singleton mode:
When there are multiple instances of an instance that can cause a program logic error
Second, the advantages:
1, reduce the memory consumption
2. Singleton mode prevents other objects from instantiating copies of their own singleton objects, ensuring that all objects have access to unique instances.
3, because the class controls the instantiation process, the class can flexibly change the instantiation process
Third, disadvantages:
1. Overhead
Although the number is small, there will still be some overhead if you want to check for instances of the class every time the object requests a reference. This problem can be resolved by using static initialization.
2. Possible development Confusion
When using singleton objects, especially those defined in a class library, developers must remember that they cannot instantiate objects using the New keyword.
Because library source code may not be accessible, application developers may unexpectedly find themselves unable to instantiate this class directly.
3. Object Lifetime
The problem of deleting a single object cannot be resolved. In a language that provides memory management, such as a. NET framework-based language, only a single class can cause an instance to be deallocated.
Because it contains a private reference to the instance. In some languages, such as C + +, other classes can delete object instances, but this results in a floating reference in a singleton class.
Iv. three modes of the singleton mode:
1. Full-Chinese style
public class Singletondemo{private Static Singletondemo instance = Null;private Singletondemo () {}public Singletondemo GetInstance () {if (instance==null) {instance = new Singletondemo ();} return instance;}}
2. A hungry man type
public class Singletondemo{private Static Singletondemo instance = new Singletondemo ();p rivate Singletondemo () {}public Singletondemo getinstance () {return instance;}}
3. Double Lock Form
This mode will synchronize the content below the if inside, improve the efficiency of the execution, do not have to synchronize every time to get the object, only the first time synchronization, created later is not necessary.
public class Singletondemo {private static Singletondemo instance = Null;private Singletondemo () {}public static Singleton Demo getinstance () {if (instance==null) {synchronized (Singletondemo.class) {if (instance==null) {instance = new Singletondemo ();}}} return instance;}}
Simple description of the singleton mode (a hungry man, full-han, double-lock mode)