java中跟踪共享对象的调用数量

来源:互联网 发布:mac上word文档丢失 编辑:程序博客网 时间:2024/06/10 23:06
package polymorphism;/** * 跟踪共享对象调用的数量 */public class ReferenceCounting {    public static void main(String[] args) {        Shared shared = new Shared();        Compsing[] compsings = {new Compsing(shared), new Compsing(shared), new Compsing(shared),                new Compsing(shared), new Compsing(shared)};        for (Compsing c : compsings)            c.dispose();    }}class Shared {    //参考数量    private int refcount = 0;    //统计实例创建的数量    private static long counter = 0;    //每创建一次实例就记一次数    private final long id = counter++;    public Shared() {        System.out.println("Creating" + this);    }    public void addRef() {        refcount++;    }    protected void dispose() {        if (--refcount == 0)            System.out.println("Disposing" + this);    }    public String toString() {        return "Shared " + id;    }}class Compsing {    private Shared shared;    private static long counter = 0;    private final long id = counter++;    public Compsing(Shared shared) {        System.out.println(this);        System.out.println("Creatting" + this);        this.shared = shared;        this.shared.addRef();    }    protected void dispose() {        System.out.println("dispose" + this);        shared.dispose();    }    public String toString() {        return "Compsing" + id;    }}
说实话这段代码看着都有点似懂非懂的感觉,虽然读懂是什么意思~ 但是不知道为什么这样设计,勉强理解!