如何判断一个类的实例是否已经存在于内存中?

4

如何判断一个类的实例是否已经存在于内存中?


我的问题是,如果类的实例已经存在,我不想读取方法。以下是我的代码:

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

我想检查PNLSpcMaster的实例,当然我可以通过静态布尔值来检查,但我认为这种方法更好。

5个回答

8
如果您想要仅有一个“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());
}

对于基本用途,单例模式非常有效。然而,对于更复杂的用途可能会存在危险。

您可以阅读更多相关内容:为什么单例模式具有争议性


1

相比于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--;
    }
}

Java的不可靠性源于它没有像C++那样提供析构函数。在Java中,由垃圾回收器来释放实例所占用的内存,但是该实例仍可能作为孤儿漂浮在内存中,因为没有其他对象引用它。因此,您永远不知道一个对象是否不再被引用。

诚然,这理论上与完全不存在于内存中是不同的,但在确定没有该类实例之前,您必须等待finalize()方法被调用。Finalizer需要警告-在时间关键的应用程序中不能依赖它们,因为在对象成为孤儿和最终化之间可能需要几秒钟到几分钟;简而言之,不能保证它们会被调用。

Dispose模式

通过实现Dispose模式,可以为解决方案增加更多的可靠性。这还要求类的客户端调用dispose方法以表示该实例将被处理,以便可以减少实例计数。编写不良的客户端将使解决方案变得不可靠。


1
我认为你想要的是单例模式 singleton

0

没有合理的方法可以找出特定类的实例是否已经存在。

如果您需要了解此信息,请创建一个静态布尔字段并从构造函数中设置它:

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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接