子类何时以及为何声明父类的静态实例成员?
这是一些遗留代码中的另一种设计模式,我在谷歌上找不到太多相关信息。在这种情况下,子类扩展其抽象父类,但然后右转并声明父类的静态实例:
public abstract class MessageBase {
protected DAOFactory factory;
// method declarations
}
public class EDWMessage extends MessageBase {
private static MessageBase instance;
public static MessageBase getInstance(Properties properties) {
if (instance == null) {
instance = new EDWMessageTransaction(properties, null);
}
return instance;
}
//more code
}
我不确定我是否理解什么会驱动此设计模式(如果它是已知模式)。这是一种避免将父级的每个成员变量声明为静态的便捷模式吗?或者它是否意味着允许多个子类每个都有一个父类的实例。但如果是这样的话,为什么要过度使用继承而不是简单的组合呢?
代码的其余部分没有说明为什么要这样做。任何想法或想法将不胜感激。谢谢!
PS我似乎遇到了很多有趣的 设计 模式在这个我不知道如何处理的遗留代码中。感谢所有已经帮助过我的人。
编辑:扩展代码示例。当我发现实际使用此代码的地方时,将再次编辑。是的,没有文档。
This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:
public abstract class MessageBase {
protected DAOFactory factory;
// method declarations
}
public class EDWMessage extends MessageBase {
private static MessageBase instance;
public static MessageBase getInstance(Properties properties) {
if (instance == null) {
instance = new EDWMessageTransaction(properties, null);
}
return instance;
}
//more code
}
I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?
The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!
P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.
Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是线程安全的惰性单例初始化的常见习惯用法。如果您可以拥有单例类,则可以委托给私有静态实例化类。
不确定这是否是您的子类的使用方式,但这将是持有其父类的静态实例的子类的用例
This is a common idiom for thread-safe lazy singleton initialization. If you can have a singleton class, you delegate to a private static instantiating class.
Not sure if this is how your child class is being used, but this would be a use case for a child class holding a static instance of its parent
最初的意图可能是,对于 MessageBase 的每个子类,应该只有 1 个实例,并且您可以使用基类中的通用方法访问该实例,
这样您就可以迭代所有消息类型并获取每个
my 2cents的实例
The original intent probably was that for each subclass of MessageBase there should only be 1 instance and that you can access that instance with a commom method in the base class
so you could iterate over all message types and get the instance of each
my 2cents