设计模式建议
我想知道是否有人可以帮助我。
假设我有一些类,如下所示:
class A { ... };
class B : public A { ... }
class C : public A { ... };
class D { ... };
class E : public D { ... };
class F : public D { ... };
现在我希望类 B 有一个类型 E 的对象作为成员,类 C 有一个类型 F 的对象作为成员。
是否有一个很好的设计模式,我可以在类 A 中拥有某种指向类 D 的基指针,然后在类 B 中创建一个新的 E,在类 C 中创建一个新的 F。我想知道抽象工厂是否类似?
我希望这不会太令人困惑……没有 UML 图很难解释!。
I was wondering if someone could help me.
Suppose I have some classes as follows:
class A { ... };
class B : public A { ... }
class C : public A { ... };
class D { ... };
class E : public D { ... };
class F : public D { ... };
Now I want class B to have an object of type E as a member and class C to have a object of type F as a member.
Is there a nice design pattern whereby I can have some sort of base pointer to class D in class A and then create a new E in class B and a new F in class C. I was wondering if abstract factory is similar?.
I hope this is not too confusing ... it is hard to explain without UML diagrams!.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
完全按照你说的做有什么问题吗?
如果您想更好地自动化它,可以使用中间模板类。
请注意,由于 协变返回类型。
What's wrong with just doing exactly as you say?
If you want to automate it a bit better, you can use an intermediate template class.
Note that
AImpl::getD()
can returnT*
due to covariant return types.您完全可以这样做:
有很多更好的方法可以实现这一点,具体取决于您想要实现的目标。例如,为什么
D
需要包含指向A
的指针?也许如果您编辑问题以更好地解释您的目标,那么我们可以提供更有洞察力的答案。
You can do exactly that:
There are many better approaches to this, depending on what you're trying to achieve. For instance, why does
D
need to contain the pointer to theA
?Perhaps if you edit your question to better explain your goal, then we can provide more insightful answers.
复合设计模式怎么样?
http://en.wikipedia.org/wiki/Composite_pattern
how about Composite Design pattern?
http://en.wikipedia.org/wiki/Composite_pattern