代码如下:
public class SingleObject {
public static SingleObject obj = new SingleObject();
public static SingleObject getInstance(){
return obj;
}
//当构造方法被private修饰后,无法被实例化
private SingleObject(){}
}
测试代码如下:
public class TestSingle {
public static void main(String[] args) {
SingleObject obj1 = SingleObject.getInstance();
SingleObject obj2 = SingleObject.getInstance();
System.out.println(obj1 == obj2);
}
}
打印结果为:true