几种单例模式
程序员文章站
2022-07-13 23:39:56
...
1.饿汉单例模式
public class Single {
public static final Single instance = new Single();
public static Single getInstance(){
return instance;
}
private Single(){
//Single诞生时要做的事情
}
public void oneMethod() {
System.out.println("I am oneMethod!");
}
}
2.懒汉单例模式
public class Single {
public static Single instance = null;
public static Single getInstance(){
if(instance == null){
instance = new Single();
}
return instance;
}
private Single(){
//Single诞生时要做的事情
}
public void oneMethod() {
System.out.println("I am oneMethod!");
}
}
3.静态内部类
public class Single {
private static class SigletonHolder {
private static Single instance = new Single();
}
public static final Single getInstance() {
return SigletonHolder.instance;
}
private Single() {
//MaYun诞生要做的事情
}
public void oneMethod() {
System.out.println("I am oneMethod!");
}
}
4.枚举单例模式
public enum Single {
NumberZero(0),
NumberOne(1),
NumberTwo(2),
NumberThree(3);
private final int value;
Single(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
上一篇: PHP单例模式
下一篇: Java中各种单例模式