Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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


My problem is that don't want read method if exist instance of Class this is my code

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

I want check instance of PNLSpcMaster of course I can check by static boolean but I think this way is better.

like image 788
Jeus Avatar asked Dec 29 '22 15:12

Jeus


2 Answers

If you want to have only one instance of "PNLSpcMaster" then you do need a singleton:

This is the common singleton idiom:

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;
   }
   ....
 }

Usage:

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

Or directly:

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

For basic usages the Singleton Pattern works very well. However for more sophisticated usages it may be dangerous.

You could read more about it: Why singletons are controversial

like image 185
OscarRyz Avatar answered Feb 20 '23 17:02

OscarRyz


I think you're after the singleton pattern.

like image 21
Andrew Avatar answered Feb 20 '23 15:02

Andrew