The concept of a singleton pattern:
The singleton pattern means that there is only one instance. The singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole. This class is called a singleton class.
Key points:
1) Only one instance of a class this is the most basic
2) It must create this instance on its own
3) It must provide this instance to the entire system on its own
--------------------------------------------------------------------------------------------------------------- -------------------------------------
Two ways to achieve this:
1 lazy mode (class loading is not initialized)
Package Singleton;
public class Lazysingleton {
Lazy Single-Case mode
Lazy, do not create an instance when the class loads, so the class loads faster, but the runtime gets the object at a slower speed
private static Lazysingleton intance = null;//static Private member, not initialized
Private Lazysingleton ()
{
Private constructors
}
public static synchronized Lazysingleton getinstance () //static, synchronous, open access point
{
if (intance = = null)
{
Intance = new Lazysingleton ();
}
return intance;
}
}
Key points: (given on code comments)
1) The constructor is defined as private----cannot get the object of the class in another class, it can only get its own object in the class itself
2) The member variable is static, not initialized----class is loaded fast, but the unique instance of the access class is slow, and static guarantees that it gets its own object in its own class
3) Public access point getinstance:public and synchronized-----Public to ensure the correctness of multiple threads while synchronizing (because class variables are not initialized at load time)
See code comments for advantages and disadvantages.
2 A Hungry man singleton mode (initialization is done when the class is loaded, so the class loads slowly but gets the object faster)
Package Singleton;
public class Eagersingleton {
A hungry man single-case mode
Initialization is done at class load, so class loading is slow, but getting objects is faster
private static Eagersingleton instance = new Eagersingleton ();//static private member, initialized
{
Private constructors
}
public static Eagersingleton getinstance () //Static, no synchronization (class load is initialized, no multi-threading issues)
{
return instance;
}
}
Key points: (code comment written)
1) Private constructors
2) Static Private member--initialized at class load
3) Public access point getinstance-----does not require synchronization because it is initialized when the class is loaded, and does not need to be judged null, directly returning
See code comments for advantages and disadvantages.
Singleton mode (Lazy way and a hungry man mode)