加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C:应用复合图案

发布时间:2020-12-16 07:13:23 所属栏目:百科 来源:网络整理
导读:我正在尝试应用Composite模式,因此我需要创建一个Leaf类和一个Composite类,它们都继承自同一个Component类.为了让我的任何组件履行其职责,他们需要从单个Helper对象请求帮助.我们有以下内容 struct Helper { void provide_help();};struct Component { Compo
我正在尝试应用Composite模式,因此我需要创建一个Leaf类和一个Composite类,它们都继承自同一个Component类.为了让我的任何组件履行其职责,他们需要从单个Helper对象请求帮助.我们有以下内容

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;
};

这里有两个不同的Leaf子类:

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;
};

通过逐个遍历m_children并在每个上调用操作本质上多次调用辅助函数,即使一个调用对所有子节点都足够.理想情况下,如果m_children由Leaf1和Leaf2组成,我想以某种方式复合操作只调用一次辅助函数,然后连续调用Leaf1 :: operation1()然后调用Leaf2 :: operation2().有没有办法达到我的需要?欢迎替代设计.我希望我的问题有道理.提前致谢!

解决方法

您需要多态操作,但是您要为方法添加更多响应(调用帮助程序).分开这两件事情会更好.

struct Component {
    void call_operation(){
        call_for_help();
        operation();
    }
    virtual void operation() = 0;
    void call_for_help();
};

从leaf :: operation()中移除call_for_help()(使operation1,operation2冗余,多态),其余的应该可以正常工作.

您甚至可以从公共界面隐藏operation(),在这种情况下,您需要与Composite建立友谊.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读