Java多个类引用同一个类的实例,可以用单例实现
运行结果如下:
代码如下:
class Single{
private static Single object;
private Single(){}
public static Single getObject(){
if(object==null) object=new Single();
return object;
}
}
class A{
public static Single getObject(){
return Single.getObject();
}
}
class B{
public static Single getObject(){
return Single.getObject();
}
}
public class Test {
public static void main(String[] args){
if(A.getObject()==B.getObject())
System.out.println("类A和类B引用了同一个类的实例");
}
}
嗯,需要个例子看看,谢谢
追答class A{
public static A instance = null;
private A(){}
public static A getInstance() {
if (instance==null)
instance = new A();
return instance;
}
}
class B{
public A getAInstance(){
return A.getInstance();
}
}
class C{
public A getAInstance(){
return A.getInstance();
}
}
public class SingletonTest {
public static void main(String[] args) {
System.out.println(new B().getAInstance()== new C().getAInstance());
}
}
输出结果为TRUE,说明是引用了同一个对象,A就是一个单例,有时间你可以看看JAVA设计模式的单例模式