繁体   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