package test1;
// 饿汉模式
class Singleton1 {
private Singleton1() {
}
private final static Singleton1 singleton = new Singleton1();
public static Singleton1 getSingleton1() {
return singleton;
}
private String name = "No";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// 懒汉模式
class Singleton2 {
private Singleton2() {
}
private static Singleton2 singleton = null;
public synchronized static Singleton2 getSingleton2() {
if (singleton == null) {
singleton = new Singleton2();
}
return singleton;
}
public int num = 0;
public synchronized void doSomething() {
System.out.println("Now the num is " + (num++));
}
}
public class SingletonTest {
public static void main(String[] args) {
// 测试单例饿汉模式
Singleton1 singleton1_1 = Singleton1.getSingleton1();
System.out.println(singleton1_1.getName());
singleton1_1.setName("Thank you.");
Singleton1 singleton1_2 = Singleton1.getSingleton1();
System.out.println(singleton1_2.getName());
// 测试单例懒汉模式
Singleton2 singleton2_1 = Singleton2.getSingleton2();
singleton2_1.doSomething();
Singleton2 singleton2_2 = Singleton2.getSingleton2();
singleton2_2.doSomething();
}
}