歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

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,這樣可以防止溢出.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

Copyright © Linux教程網 All Rights Reserved