public class SimpleDemo1 {
//恶汉式
//类初始化时,立即加载这个对象(没有延时加载的优势)。加载类时,天然的是线程安全的
private static final SimpleDemo1 instance = new SimpleDemo1();
private SimpleDemo1(){
}
//方法不用同步,调用效率高
public static SimpleDemo1 getInstance(){
return instance;
}
}
public class SimpleDemo2 {
//懒汉式
//类初始化时,不初始化这个对象(延时加载,真正用的时候再创建)
private static SimpleDemo2 instance ;
private SimpleDemo2(){
}
//方法同步,调用效率低!
public synchronized static SimpleDemo2 getInstance(){
if(null == instance){
instance = new SimpleDemo2();
}
return instance;
}
}
public class SimpleDemo3 {
//静态内部类的方式
//这种方式:线程安全,调用效率高,并且实现了延时加载!
private static class SingleClassInstance{
private static final SimpleDemo3 instance = new SimpleDemo3();
}
//方法没有同步,调用效率高
public static SimpleDemo3 getInstance(){
return SingleClassInstance.instance;
}
private SimpleDemo3(){
}
}
public enum SimpleDemo4 {
//枚举方式
INSTANCE;
public void instanceOpration(){
System.out.println("hah");
}
}
public class Test {
/*
* 测试单例模式
*/
public static void main(String[] args){
SimpleDemo1 s1 = SimpleDemo1.getInstance();
SimpleDemo1 s2 = SimpleDemo1.getInstance();
System.out.println(s1);
System.out.println(s2);
SimpleDemo2 s3 = SimpleDemo2.getInstance();
SimpleDemo2 s4 = SimpleDemo2.getInstance();
System.out.println(s3);
System.out.println(s4);
SimpleDemo3 s5 = SimpleDemo3.getInstance();
SimpleDemo3 s6 = SimpleDemo3.getInstance();
System.out.println(s5);
System.out.println(s6);
SimpleDemo4 s7 = SimpleDemo4.INSTANCE;
SimpleDemo4 s8 = SimpleDemo4.INSTANCE;
System.out.println(s7);
System.out.println(s8);
SimpleDemo4.INSTANCE.instanceOpration();
}
}