簡體   English   中英

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

[英]How can I know whether an instance of a class already exists in memory?

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


我的問題是,如果存在Class的實例,這是我的代碼,不想讀取方法

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

我想檢查PNLSpcMaster的實例當然我可以通過靜態布爾檢查,但我認為這種方式更好。

如果您只想擁有一個“PNLSpcMaster”實例,那么您需要一個單例

這是常見的單身成語:

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非常有效。 然而,對於更復雜的用法,它可能是危險的。

你可以閱讀更多關於它的內容: 為什么單身人士會引起爭議

我認為你是在追隨單身人士模式。

與C ++相反,有幾個因素有助於在Java中獲得可靠的解決方案。

以下示例不可靠,但如果您使用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模式為解決方案添加更多可靠性。 這還要求類的客戶端調用dispose方法來發信號通知實例將被丟棄,以便可以減少實例計數。 寫得不好的客戶會使解決方案不可靠。

沒有合理的方法來確定特定類的實例是否已經存在。

如果您需要知道此信息,請創建一個靜態布爾字段並從構造函數中設置它:

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

對於具有標識概念的類,將應用標識映射模式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM