1. 示例代码
package com.fqyuan.thinking;
class Shared {
private int refcount = 0;
private static long count = 0;
private final long id = count++;
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 Composing {
private Shared shared;
private static long counter = 0;
private final long id = counter++;
public Composing(Shared shared) {
System.out.println("Creating " + this);
this.shared = shared;
this.shared.addRef();
}
protected void dispose() {
System.out.println("Disposing " + this);
shared.dispose();
}
public String toString() {
return "Composing " + id;
}
}
public class ReferencingCounting {
public static void main(String[] args) {
Shared shared = new Shared();
Composing[] composing = { new Composing(shared), new Composing(shared), new Composing(shared),
new Composing(shared), new Composing(shared), new Composing(shared) };
for (Composing c : composing)
c.dispose();
}
}
Creating Shared 0
Creating Composing 0
Creating Composing 1
Creating Composing 2
Creating Composing 3
Creating Composing 4
Creating Composing 5
Disposing Composing 0
Disposing Composing 1
Disposing Composing 2
Disposing Composing 3
Disposing Composing 4
Disposing Composing 5
Disposing Shared 0
2. 代码解释
- 在Shared对象中有三个成员变量:refcount, count, id.
- 其中refcount为private int 类型的,代表了给定该Shared类的某个具体对象被使用的次数。在每次使用某个给定的实例后,主动调用addRef()方法完成引用数值的增加。
- count为private static long类型的,表明该类被用来new对象的总次数,因为是static 类型的,表明该成员变量为该类所共用。它的改变会随着每次new对象时增加。
- id为private final long类型的,是用来生成新对象标识的机制。通过使用id = count++实现了id的更新,同时更新了count的值。
因为这些变量都是类成员变量,所以在类创建时就会自动初始化。