public class HelloWorld{
public static void main(String []args){
SingleObject s = SingleObject.getInstance();
System.out.println(s);
SingleObject s2 = SingleObject.getInstance();
System.out.println(s2);
System.out.println(s == s2);
s.say();
}
}
//单例双重检查方式
class SingleObject{
private volatile static SingleObject in=null;
private SingleObject(){}
public static SingleObject getInstance(){
if(in == null){
synchronized(SingleObject.class){
if(in == null){
in = new SingleObject();
}
}
}
return in;
}
public void say(){
System.out.println("say hi");
}
}
//静态内部类
class SingleObject{
public static class SingleObjectInner{
private static final SingleObject INSTANCE = new SingleObject();
}
private SingleObject(){}
public static SingleObject getInstance(){
return SingleObjectInner.INSTANCE;
}
public void say(){
System.out.println("say hi");
}
}