简体   繁体   中英

C++: Applying the Composite pattern

I am trying to apply the Composite pattern, so I need to create a Leaf class and a Composite class, both inheriting from the same Component class. In order for any of my Components to perform their duty they need to ask help from a single Helper object. We have the following

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

And here are two different Leaf subclasses:

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

So far, so good. Now the Composite class is giving me grief. The typical implementation is as follows

struct Composite
: Component {

    Composite(Helper* helper)
    : Component(helper) {
    }

    void operation() override {
        for (auto el : m_children) el->operation();
    }

private:
    std::vector<Component*> m_children;
};

which by going through the m_children one by one and calling operation on each essentially calls the helper function multiple times, even though one call is enough for all children. Ideally, if the m_children consisted, say, of a Leaf1 and a Leaf2 , I would like somehow the Composite operation to call the helper function only once and then call in succession Leaf1::operation1() and then Leaf2::operation2(). Is there any way to achieve what I need? Alternative designs are welcome. I hope my question makes sense. Thanks in advance!

You want a polymorphic operation but you are adding more responability to the method (calling the helper). It's better to separate these two things.

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

Remove the call_for_help() from leaf::operation() (making operation1, operation2 redundant, polymorphism) and the rest should work fine.

You can even hide operation() from your public interface, you'll need friendship with your Composite in that case.

As it could happen at any level, one approach could be to handle this at the level of the helper.

A sketch of the approach would be:

class Helper {
    bool composite_help = false;
    bool help_provided;  
public:     
    void provide_help() { 
       if ((composite_help && !help_provided) || !composite_help) {
           //TO DO: provide help
           help_provided = true;
       }
     }   
    void start_composite_help() {
       composite_help = true; 
       help_provided = false;
    } 
    void end_composite_help() {
       composite_help = false; 
    } 
};

The principle is that the call for help performed by individual components works as before. But when the composite calls for help, you take preacutions to make sure that the call is performed only once:

void operation() override {
    m_helper->start_composite_help(); 
    for (auto el : m_children) el->operation();
    m_helper->start_composite_help(); 
}

As said, this is only a sketch: the code provided as such will not work as soon as you have several levels of composites. So this needs to be improved:

  • instead of a bool composite_help you'd need a counter, which gets incremented when entering a composite operation and decremented when you exit it. In this case, the counter would go back to 0 (re-enabling help) only when the last level of composte has finished its job.

  • may be the helper performs different operations to provide help. So you could also imagine to have a "transaction id" that uniquely identifies a group of related operations, and you manage the counter not for the helper overall, in a map of active transactions.

  • finally, the start/end is not so nice. A RAII helper to the helper could make the whole setup more robust (for example when an exception breaks the normal execution flow.)

I think this problem would be better solved with a combination of Composite and Mediator .

Heads up! I'll show you a different version of the mediator pattern, which is not the same as the canonical version.

It's not of the business of your composite structure to know if a helper was called or not. You'd better do this using some kind of event handler.

Since you have only one helper, you could try like this:

class Helper {
    public:
        void callHelper() { std::cout << "Helper called" << std::endl; }
};

class Mediator {
    private:
        std::map<std::string, std::vector<Helper>> subscribers;
        int updateLimit = -1;
        int currentUpdateCount = 0;

        void resetUpdateCount() {
            currentUpdateCount = 0;
        }
    public:
        Mediator(){}

        void subscribe(std::string evt, Helper helper) {
            subscribers[evt].push_back(helper);
        }

        void update(std::string evt) {
            for (auto& h: subscribers[evt]) {
                h.callHelper();
            }
        }

        void setUpdateLimit(int i) {
            updateLimit = i;
            resetUpdateCount();
        }

        void removeUpdateLimit() {
            updateLimit = -1;
            resetUpdateCount();
        }

        int getUpdateLimit() {
            return updateLimit;
        }


        void updateLimited(std::string evt) {
            if (updateLimit < 0 || currentUpdateCount < updateLimit) {
                update(evt);
                currentUpdateCount++;
            } 
        }
};

int main(int argc, const char *argv[])
{

    Mediator m;
    Helper h1, h2;
    m.subscribe("bar", h1);


    m.setUpdateLimit(1);
    // Will be called only once
    m.updateLimited("bar");
    m.updateLimited("bar");
    m.updateLimited("bar");
    m.removeUpdateLimit();

    return 0;
}

Using it:

Mediator m;
Helper h1, h2;
m.subscribe("bar", h1);


m.setUpdateLimit(1);
// Will be called only once
m.updateLimited("bar");
m.updateLimited("bar");
m.updateLimited("bar");
m.removeUpdateLimit();

So, here is what you do to integrate this to you composite structure. Remove the helper from you nodes, add the Mediator to the base class:

struct Component {

    Component(Mediator& mediator)
    : m_helper(mediator) {
    }

    virtual void operation() = 0;

    //    the call_for_help function will be used by subclasses of Component to implement Component::operation()

    void notify() {
        m_mediator->updateFiltered(Component::updateEventName);
    }
    static std::string updateEventName;
private:
    Mediator& m_mediator;
};

std::string Component::updateEventName = "update.composite";

struct Leaf1
: Component {

    Leaf1(Helper* helper)
    : Component(helper) {
    }

    void operation() override {
        notify();
        operation1();
    }

    void operation1();
};

Using it:

Mediator m;
Helper h;

Composite c(m);
Leaf1 l1(m), l2(m);
c.add(l1);
c.add(l2);

m.subscribe(Component::updateEventName, h);

m.setUpdateLimit(1);
// Will be called only once, even if it has childrens
c.update();
m.removeUpdateLimit();

IMPORTANT: This solution is suboptimal, it has some issues, like you having to pass a mediator instance to every node constructor, but it's just a raw idea for you to work on.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM