conditions of Use: You can use this mode when you only need a unique object for a class in your system .
Why is this pattern used? : Because sometimes the creation of some objects requires a lot of resources, using a single (unique) object instance to maintain some shared data, and so on, in these scenarios can be designed in a single-case mode, it is appropriate to reduce the memory overhead, because the unique object is not (limited) to create frequently.
The first type: full-han mode
public class singleton{
Private SingleTon () {};
private static SingleTon instance = new SingleTon ();
public static SingleTon getinstance ()
{
return instance;
}
}
The second type: Hunger and Han Mode
public class singleton{
Private SingleTon () {};
private static SingleTon instance = Null;//new singletonight ();
public static synchronized SingleTon getinstance ()
{
if (instance==null) instance = new SingleTon ();
return instance;
}
}
This method is better than the above method, not every time the generation of objects, but the first use of the build instance, improve efficiency.
Noting the second form of synchronized, this synchronized is important, if not synchronizedThere can be confusion when a thread accesses it at the same time, so we can add it before the methodsynchronizedkeyword to ensure that it is accessed synchronously.
in a comprehensive sense,
is to not give the outside world the chance to call their own construction method,
You can only get instances of this class by means such as getinstance (),
and this instance has already been generated,
can only be called,
cannot be created,
This ensures that only one instance of a class exists in a Java application.
Singleton mode (Singleton)