package testsingle;
//实现单例的两种方式
public class TestMySingle {
public static void main(String[] args) {
ClassA ca1 = ClassA.getClassA();
ClassA ca2 = ClassA.getClassA();
System.out.println(ca1==ca2);
ClassB cb1 = ClassB.getClassB();
ClassB cb2 = ClassB.getClassB();
System.out.println(cb1==cb2);
}
}
class ClassA{ //饿汉式
private static final ClassA ca = new ClassA();
private ClassA(){}
public static ClassA getClassA(){
return ca;
}
}
class ClassB{ //懒汉式
private static ClassB cb ;
private ClassB(){}
public synchronized static ClassB getClassB(){
if(cb==null){
cb = new ClassB();
}
return cb;
}
}