Singleton design pattern (that is, a class has only one object in memory)
Ideas:
1. Privatize the constructor
2. Create an object yourself in the class
3. Provides a way to get the object
Cases:
public Class A single {
Singleton design pattern (a class that only has one object in memory)
Private single () {///is set to proprietary so that it cannot be new out of the object
}
private static single s=new single (); Customizing an Object
public static single getinstance () {//Use (class name. static function) to return the object that you defined
return s;
}
private int age;
public void Setage (int.) {
This.age=age;
}
public int getage () {
return age;
}
}
The use of the Main method
Single s6=single.getinstance ();//Returns the custom object by (class name. static function)
Single s2=single.getinstance ();//Returns the custom object by (class name. static function)
S6.setage (36);
System.out.println (S2.getage ()); Print out 36, indicating that only one object exists in memory
System.err.println (S6);//The address value of the object is the same
SYSTEM.OUT.PRINTLN (S2);//The address value of the object is the same
Java single-Instance design pattern