加入收藏 | 设为首页 | 会员中心 | 我要投稿 开发网_郴州站长网 (http://www.0735zz.com/)- 云通信、区块链、物联设备、云计算、站长网!
当前位置: 首页 > 教程 > 正文

Java static和final的巧妙实施

发布时间:2021-12-14 15:07:42 所属栏目:教程 来源:互联网
导读:监听当前对象被创建了几个..我们可以用一个static来确定个数.(此处说明下为什么要用static:一个类中静态变量只会被初始化一次,不管你实例化多少个类,里面始终只有一个). 下面是使用计数来跟踪仍旧访问着共享对象的对象数量: package com.glacier.demo; class
监听当前对象被创建了几个..我们可以用一个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,这样可以防止溢出.id是final类型的,我们不希望它在生命周期中改变.
 
在将一个共享对象附到类上时,必须记住调用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

(编辑:开发网_郴州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读