单例模式能够确保一个类只有一个实例。自行提供这个实例并向整个系统提供这个实例。
package JAVA_Project_01_05;
class OneSingleton {
private static int number = 0;
private static OneSingleton instance = new OneSingleton();
private OneSingleton() {
}
public static OneSingleton getInstance() {
return instance;
}
public synchronized int getNumber() {
return number;
}
public synchronized void nextNumber() {
number++;
}
}
class TwoSingleton {
private static int number = 0;
private static TwoSingleton instance = null;
private TwoSingleton() {
}
public static synchronized TwoSingleton getInstance() {
if (instance == null) {
instance = new TwoSingleton();
}
return instance;
}
public synchronized int getNumber() {
return number;
}
public synchronized void nextNumber() {
number++;
}
}
public class TextSingleton {
public static void main(String[] args) {
OneSingleton one1 = OneSingleton.getInstance();
OneSingleton one2 = OneSingleton.getInstance();
System.out.println("用OneSingleton实现单例模式");
System.out.println("调用nextNumber方法前:");
System.out.println("one1.number=" + one1.getNumber());
System.out.println("one2.number=" + one2.getNumber());
one1.nextNumber();
System.out.println("调用nextNumber方法后:");
System.out.println("one1.number=" + one1.getNumber());
System.out.println("one2.number=" + one2.getNumber());
TwoSingleton two1 = TwoSingleton.getInstance();
TwoSingleton two2 = TwoSingleton.getInstance();
System.out.println("用TwoSingleton实现单例模式");
System.out.println("调用nextNumber方法前:");
System.out.println("two1.number=" + two1.getNumber());
System.out.println("two2.number=" + two2.getNumber());
two1.nextNumber();
System.out.println("调用nextNumber方法后:");
System.out.println("two1.number=" + two1.getNumber());
System.out.println("two2.number=" + two2.getNumber());
}
}