- public class Test {
- public static void main(String[] args) {
- Danli a = Danli.getInstance();
- Danli b = Danli.getInstance();
- Danli c = Danli.getInstance();
- Danli d = Danli.getInstance();
- System.out.println(a + "," + b + "," + c);
- //由这里的打印结果也可以看出来都是指向的是一个内存地址
- //org.zq.test.Danli@527c6768,org.zq.test.Danli@527c6768,org.zq.test.Danli@527c6768
- }
- }
- class Danli{
- /*
- private Danli(){}
-
- private static Danli danli;
-
- public static Danli getInstance(){
- if(danli == null){
- danli = new Danli();
- }
- return danli;
- } */
-
- private Danli(){} //私有构造函数,外部就不能直接访问,
-
- private static Danli danli = new Danli();
- //用static 表示该对象存在与内存中的未实例化之前就存在了,并且也私有化了,外部不能直接访问
- public static Danli getInstance(){
- return danli; //这里提供一个访问方法,返回的是成员变量,并且是共享数据
- //由于private static Danli danli = new Danli();
- //danli 已经在内存中存在,且是该类的成员属性,再次创建对象获取的时候也是这个数据共享区中的对象
- //就保证了,这个对象只能存在一个,。
-
- }
- }
复制代码
|