Singleton
It is a creation-type design model. It maintains only one object in a class and has only one object in life, such as the Earth, the Sun, and the universe. A singleton can also be used to set a class as a singleton without changing the object information.
There are two methods for singleton: lazy and ELE. Me.
Implementation of singleton:
Step 1: Change the constructor to private
Step 2: Use this class object as the static property of this class.
Step 3: use static methods to obtain static attributes of the class
The Code is as follows:
Lazy style (Kaige upgraded version ):
Advantage: Memory saving. If this object is not used, the memory will not be wasted.
Disadvantage: the invocation is slow.
Package com.cn. xfonlineclass2;
Public class dog {
Private string name;
Private int age;
Private string sex;
Private Static dog = NULL;
Private dog (string name, string sex, int age ){
This. Name = Name;
This. Age = age;
This. Sex = sex;
}
Public static dog getdog (){
If (dog = NULL ){
Synchronized (dog. Class ){
If (dog = NULL ){
Dog = new dog ("trademanager", "female", 4 );
}
}
}
Return dog;
}
Public String tostring (){
Return "name:" + name + "\ t Gender:" + sex + "\ t age:" + age;
}
}
Hungry Chinese style:
Advantage: the access is fast and the fastest way to get new objects.
Disadvantage: If no object is needed, the memory will be occupied, resulting in a waste of memory.
Package com.cn. xfonlineclass2;
Public class dog {
Private string name;
Private int age;
Private string sex;
Private Static dog = new dog ("", "Xiong", 3 );
Private dog (string name, string sex, int age ){
This. Name = Name;
This. Age = age;
This. Sex = sex;
}
Public static dog getdog (){
Return dog;
}
Public String tostring (){
Return "name:" + name + "\ t Gender:" + sex + "\ t age:" + age;
}
}
Test class:
Package com.cn. xfonlineclass2;
Public class test {
Public static void main (string [] ARGs ){
System. Out. println (dog. getdog ());
}
}
Note: The main method should be separated from the class to be tested. If you create a main method in the class to be tested, it means that you can access private variables in this class.