第一种:package singleton;
/**
* 简单的方式,在并发执行时可能存在多个实例
* @author WuPeng
*
*/
public class SingletonDemo1 {
private static SingletonDemo1 INSTANCE;
private SingletonDemo1() {}
public static SingletonDemo1 getInstance() {
if(INSTANCE == null) {
INSTANCE = new SingletonDemo1();
}
return INSTANCE;
}
}
第二种:
package singleton;
/**
* 公共域方式:简单
* @author WuPeng
*
*/
public class SingletonDemo2 {
public static final SingletonDemo2 INSTANCE = new SingletonDemo2();
private SingletonDemo2() {}
}
第三种:
package singleton;
/**
* 工厂模式:可以在实例过程中添加逻辑
* @author WuPeng
*
*/
public class SingletonDemo3 {
public static final SingletonDemo3 INSTANCE = new SingletonDemo3();
private SingletonDemo3() {}
public static SingletonDemo3 getInstance() {
return INSTANCE;
}
}
第四种:
package singleton;
/**
* 枚举类方式:最佳实践,推荐
* @author WuPeng
*
*/
public enum SingletonDemo4 {
INSTANCE;
public void say(String str) {
System.out.println("Hello "+str);
}
}
通过测试可以看出区别:
package singleton;
public class TestSingleton {
public static void main(String[] args) {
System.out.println("SingletonDemo1:"+SingletonDemo1.getInstance());
System.out.println("SingletonDemo1:"+SingletonDemo1.getInstance());
System.out.println("SingletonDemo2:"+SingletonDemo2.INSTANCE);
System.out.println("SingletonDemo2:"+SingletonDemo2.INSTANCE);
System.out.println("SingletonDemo3:"+SingletonDemo3.getInstance());
System.out.println("SingletonDemo3:"+SingletonDemo3.getInstance());
System.out.println("SingletonDemo4:"+SingletonDemo4.INSTANCE);
System.out.println("SingletonDemo4:"+SingletonDemo4.INSTANCE);
SingletonDemo4.INSTANCE.say("java");
}
}
|
|