java static和final的巧妙应用

监听当前对象被创建了几个..我们可以用一个static来确定个数.(此处说明下为什么要用static:一个类中静态变量只会被初始化一次,不管你实例化多少个类,里面始终只有一个).

下面是使用计数来跟踪仍旧访问着共享对象的对象数量:

package com.glacier.demo;

class Shared {
	private int refcount = 0;
	private 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 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 "Compsing " + id;
	}
}

public class Demo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Shared shared = new Shared();
		Composing[] composing = { new Composing(shared), new Composing(shared),
				new Composing(shared), new Composing(shared),
				new Composing(shared) };
		for (Composing c : composing) {
			c.dispose();
		}
	}

}


static long counter 跟踪所创建的shared的实例的数量,还可以为id提供数值.counter的类型是long而不是int,这样可以防止溢出.idfinal类型的,我们不希望它在生命周期中改变.

在将一个共享对象附到类上时,必须记住调用addRef(),但是dispose()方法将跟踪引用数,并决定何时执行清理.使用这种技巧需要加倍细心.


看下运行结果:

Creating Shared 0
Creating Compsing 0
Creating Compsing 1
Creating Compsing 2
Creating Compsing 3
Creating Compsing 4
disposing Compsing 0
disposing Compsing 1
disposing Compsing 2
disposing Compsing 3
disposing Compsing 4



你可能感兴趣的:(java static和final的巧妙应用)