如何知道内存中是否已经存在类的实例?
我的问题是,如果存在类实例,则不想读取方法
这是我的代码
private void jButton (java.awt.event.ActionEvent evt) {
PNLSpcMaster pnlSpc = new PNLSpcMaster();
jtabbedPanel.addTab("reg",pnlSpc);
}
我想检查以下实例PNLSpcMaster
当然我可以通过静态布尔检查,但我认为这种方式更好。
如果您只想拥有一个“PNLSpcMaster”实例,那么您确实需要一个单身人士 https://stackoverflow.com/questions/1441984/how-can-i-know-whether-an-instance-of-a-class-already-exists-in-memory/1442004#1442004:
这是常见的单例习惯用法:
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);
}
或者直接:
private void jButton (java.awt.event.ActionEvent evt) {
jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}
对于基本用法单例模式 http://en.wikipedia.org/wiki/Singleton_pattern效果很好。然而,对于更复杂的用途,这可能是危险的。
您可以阅读更多相关内容:为什么单例会引起争议 http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)