饿汉模式
public class Persident{
private static Persident p = new Persident();
private Persident(){
System.out.println("产生一位总统");
}
public static Persident getInstance(){
return p;
}
}
在main函数中
Persident p1 = Persident.getInstance();
Persident p2 = Persident.getInstance();
在控制台只会输出一个: 产生一位总统
懒汉模式
public class Persident{
private static Persident p;
private Persident(){
System.out.println("产生一位总统");
}
public static Persident getInstance(){
if (p == null) {
p = new Persident();
}
return p;
}
}
在main函数中
Persident p1 = Persident.getInstance();
Persident p2 = Persident.getInstance();
在控制台只会输出一个: 产生一位总统