我怎么知道一个类的实例是否已经存在于内存中?
我的问题是,如果存在Class的实例,这是我的代码,不想读取方法
private void jButton (java.awt.event.ActionEvent evt) {
PNLSpcMaster pnlSpc = new PNLSpcMaster();
jtabbedPanel.addTab("reg",pnlSpc);
}
Run Code Online (Sandbox Code Playgroud)
我想检查实例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;
}
....
}
Run Code Online (Sandbox Code Playgroud)
用法:
private void jButton (java.awt.event.ActionEvent evt) {
// You'll get the "only" instance.
PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance()
jtabbedPanel.addTab("reg",pnlSpc);
}
Run Code Online (Sandbox Code Playgroud)
或直接:
private void jButton (java.awt.event.ActionEvent evt) {
jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}
Run Code Online (Sandbox Code Playgroud)
对于基本用法,Singleton Pattern非常有效.然而,对于更复杂的用法,它可能是危险的.
你可以阅读更多关于它的内容:为什么单身人士会引起争议