If you want the object of a class to exist only one, you can use the singleton design pattern, the single-case design is divided into Russian-Chinese and lazy-type
First look at the Russian-Chinese style:
Single case Russian-Chinese style
Class single1{
Private Single1 () {};
private static Single1 Single1 = new Single1 ();
public static Single1 GetSingle1 () {
return single1;
}
}
Since the object of the Single1 class is guaranteed to exist only one, it is not allowed to create objects of this class, to privatize the constructor: Private Single1 () {};
The other person can not create the object of this class, how to let others get the object of this class, you provide a method GetSingle1 (), to return this object, others can not create the object of this class,
So this method cannot be called by object, it can be called by the class name. GetSingle1 (), so this method is declared as static, and this method is going to return single1, so Single1
Also defined as static: private static Single1 single1 = new Single1 ();
Call this object:
public class Singledemo {
public static void Main (string[] args) {
Invokes a class-supplied method to produce a unique object of a class
Single1 S1 = Single1.getsingle1 ();
}
}
The other is a lazy type:
Class single{
Private single () {};
private static single = NULL;
//In order to prevent multi-threaded operation, you can lock, use synchronized block or add synchronized on the method line
public Static/* synchronized*/ single Getsingle () {
if (null==single) {//empty only to enter lock, improve performance
synchronized (single.class) {
if (null==single) {
single = new single ();
}
}
}
return Single;
}
public void Show () {
System.out.println ("Dasini");
}
}
Call:
public class Singledemo {
public static void Main (string[] args) {
Invokes a class-supplied method to produce a unique object of a class
Single S1 = Single.getsingle ();
Single S2 = Single.getsingle ();
System.out.println (S1); The same [email protected]
SYSTEM.OUT.PRINTLN (S2); The same [email protected]
System.out.println (S1==S2); True indicates the same object, guaranteeing the uniqueness of the object
Single.getsingle (). Show ();
}
}
Hope to help you!!!
A singleton design pattern in Java