/**
* 简单的方式,在并发执行时可能存在多个实例
* @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;
}
}
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());