懒汉模式
public class Demo2 {
private static Demo1 demo = null;
public Demo2() {
}
private static Demo1 getInstance() {
if (demo == null) {
synchronized (Demo2.class) {
if (demo == null) {
demo = new Demo1();
}
}
}
return demo;
}
}
饿汉模式
public class Demo3 {
public Demo3() {
}
private static Demo1 demo = new Demo1();
private static Demo1 getInstance() {
return demo;
}
}
静态内部类模式
public class Demo4 {
public Demo4() {
}
private static class DemoHolder {
private static final Demo1 DEMO = new Demo1();
}
private static Demo1 getInstance() {
return DemoHolder.DEMO;
}
}
枚举模式
public class Demo5 {
public static void main(String[] args) {
DemoEnum.DEMO.getDemo();
}
public enum DemoEnum {
DEMO;
private Demo1 demo;
public Demo1 getDemo() {
return demo;
}
DemoEnum() {
this.demo = new Demo1();
System.out.println("111");
}
}
}