2009-09-18 27 views
3

如何知道內存中是否存在類的實例?我怎麼知道一個類的實例是否已經存在於內存中?


我的問題是,不希望閱讀方法是否存在 類的實例,這是我的代碼

private void jButton (java.awt.event.ActionEvent evt) { 
    PNLSpcMaster pnlSpc = new PNLSpcMaster(); 
    jtabbedPanel.addTab("reg",pnlSpc); 
} 

我要檢查,當然PNLSpcMaster比如我可以通過靜態布爾但我檢查認爲這種方式更好。

回答

7

如果你想擁有的 「PNLSpcMaster」 那麼你do need a singleton只有一個實例:

這是常見的單成語:

public class PNLSpcMaster { 

    /** 
    * This class attribute will be the only "instance" of this class 
    * It is private so none can reach it directly. 
    * And is "static" so it does not need "instances" 
    */   
    private static PNLSpcMaster instance; 

    /** 
    * Constructor make private, to enforce the non-instantiation of the 
    * class. So an invocation to: new PNLSpcMaster() outside of this class 
    * won't be allowed. 
    */ 
    private PNLSpcMaster(){} // avoid instantiation. 

    /** 
    * This class method returns the "only" instance available for this class 
    * If the instance is still null, it gets instantiated. 
    * Being a class method you can call it from anywhere and it will 
    * always return the same instance. 
    */ 
    public static PNLSpcMaster getInstance() { 
     if(instance == null) { 
      instance = new PNLSpcMaster(); 
     } 
     return instance; 
    } 
    .... 
} 

用法:

private void jButton (java.awt.event.ActionEvent evt) { 
    // You'll get the "only" instance.   
    PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance() 
    jtabbedPanel.addTab("reg",pnlSpc); 
} 

或者直接:

private void jButton (java.awt.event.ActionEvent evt) { 
    jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace()); 
} 

基本用法Singleton Pattern工作得很好。然而,對於更復雜的用法,這可能是危險的。

您可以閱讀更多關於它的信息:Why singletons are controversial

0

找出某個特定類的實例是否已經存在沒有合理的方法。

如果您需要了解這些信息,創建一個靜態布爾字段,並從構造函數設置:

class MyClass { 
    private static bool instanceExists = false; 
    public MyClass() { 
     MyClass.instanceExists = true; 
    } 
} 
0

有幾個因素會有助於在Java中獲得可靠的解決方案,而不是C++。

以下示例不可靠,但如果使用hasAtleastOne()方法,它可以爲您提供足夠正確的答案。

class Example { 
    private static int noOfInstances = 0; 

    public Example() { 
     noOfInstances++; 
    } 


    public static boolean hasAtleastOne() { 
     if(noOfInstances > 0) 
      return true; 
     else 
      return false; 
    } 

    protected void finalize() throws Throwable { 
     noOfInstances--; 
    } 
} 

不像C++那樣,不可靠性源於事實上析構函數在Java中不可用。直到垃圾收集器釋放實例消耗的內存 - 由於沒有其他對象引用該實例,因此實例仍然可以作爲孤兒在內存中浮動。因此,你永遠不知道對象是否不再被引用。不可否認,這與理論上不同於在內存中根本不存在,但是在確定沒有這種類的實例可用之前,您必須等待finalize()方法被調用。終結器會帶來警告 - 它們不能在時間關鍵的應用中使用,因爲它可能是物體孤立和終結之間的幾分鐘到幾分鐘的因素;總之,不能保證他們可以被稱爲。

的Dispose模式

您可以通過實施the Dispose pattern增加更多可靠性的解決方案。這也要求該類的客戶調用dispose方法來發信號通知該實例將被處置,從而可以減少實例計數。寫得不好的客戶會使解決方案不可靠。

相關問題