我想要应用复合模式,所以我需要创建一个Leaf类和一个Composite类,它们都从相同的Component类继承。为了我的组件的任何执行他们的责任,他们需要从单个帮助对象请求帮助。我们有以下C++:应用复合模式
struct Helper {
void provide_help();
};
struct Component {
Component(Helper* helper)
: m_helper(helper) {
}
virtual void operation() = 0;
// the call_for_help function will be used by subclasses of Component to implement Component::operation()
void call_for_help() {
m_helper->provide_help();
}
private:
Helper* m_helper;
};
,这里是两个不同的子类叶:
struct Leaf1
: Component {
Leaf1(Helper* helper)
: Component(helper) {
}
void operation() override {
call_for_help();
operation1();
}
void operation1();
};
struct Leaf2
: Component {
Leaf2(Helper* helper)
: Component(helper) {
}
void operation() override {
call_for_help();
operation2();
}
void operation2();
};
到目前为止,一切都很好。现在复合班正在给我悲伤。典型的实现是
struct Composite
: Component {
Composite(Helper* helper)
: Component(helper) {
}
void operation() override {
for (auto el : m_children) el->operation();
}
private:
std::vector<Component*> m_children;
};
它由一个通过一个会,并呼吁各operation
基本调用辅助函数多次,即使一个电话就足够了所有的孩子。理想情况下,如果包含Leaf1
和Leaf2
,我希望Composite操作只调用一次helper函数,然后调用Leaf1 :: operation1(),然后调用Leaf2 :: operation2()。有什么方法可以实现我需要的吗?替代设计是受欢迎的。我希望我的问题有道理。提前致谢!
根据你的结构,每个孩子都可以有不同的帮手。你期望什么:每个不同的帮手应该只被称为一个?或者你确定同一个组合的所有叶子都共享同一个助手吗? – Christophe
@Christophe:嗨,只有一个帮手。所以是的,我希望同一个复合材料的所有叶子共享相同的助手。 – linuxfever
感谢大家的所有详细和有用的答案! – linuxfever