When to use a single case mode:
When there are multiple instances that can cause procedural logic errors
Second, the benefits:
1, reduce the memory consumption
2. The singleton mode prevents other objects from instantiating copies of their own singleton objects, ensuring that all objects have access to a unique instance.
3, because the class controls the instantiation process, so the class can flexibly change the instantiation process
Third, shortcomings:
1. Cost
Although the number is small, some overhead will still be required if you want to check for instances of the class each time the object requests a reference. You can resolve this problem by using static initialization.
2. Possible development Confusion
When working with Singleton objects, especially those defined in class libraries, developers must remember that they cannot instantiate objects using the New keyword.
Because the library source code may not be accessible, application developers may accidentally find themselves unable to instantiate the class directly.
3. Object Lifetime
The problem of deleting a single object cannot be resolved. In a language that provides memory management (for example, a language based on the. NET framework), only singleton classes can cause instances to be unassigned.
Because it contains a private reference to the instance. In some languages, such as C + +, other classes can delete an object instance, but this can result in a floating reference in a singleton class.
Iv. three modes of single case pattern:
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 ();
Private Singletondemo () {
} public
Singletondemo getinstance () {return
instance;
}
}
3. Double Lock Form
This mode will synchronize the content below to the if internal, improve the efficiency of execution, do not have to get the object every time the synchronization, only the first synchronization, created after the unnecessary.
public class Singletondemo {
private static Singletondemo instance = null;
Private Singletondemo () {
} public
static Singletondemo getinstance () {
if (instance==null) {
Synchronized (singletondemo.class) {
if (instance==null) {
instance = new Singletondemo ();
}
}
} Return
instance
}
}