Composite mode and C ++ implementation

Composite mode

Composite class to maintain a parent class (pointer) to the list of elements, it is actually a proxy parent class, but can be used anywhere in the parent class or subclass other parent can also use the Composite class.

C ++ implementation

/*这个Composite模式的实现是在实现Command模式的代码的基础上更改的,两个可以比较着看*/
#include<iostream>
#include<vector>
using namespace std;
 
class Command {
public:
    virtual void doit() {
        cout << "command\n";
    }
};

//在CompositeCommand类中维护一个Command*的列表
//让CompositeCommand继承Command类,这样凡是可以用Command的地方都可以用CompositeCommand
//这样就实现了执行一个命令的代码和执行若干个命令的代码是一样的
class CompositeCommand : public Command {
public:
    virtual void doit() {
        for (auto i = commands.begin(); i != commands.end(); ++i) {
            Command* command = *i;//*i -> doit(): error, 'cause *i isn't taken as a pointer
            command->doit();
        }
    }
    void add(Command* command) {//为了简单,这里只写了添加命令的代码,没写删除命令的
        commands.push_back(command);
    }
private:
    vector<Command*> commands;
};

//下面是会绑定到Sensor上的三个命令
class TurnonCommand : public Command {
public:
    virtual void doit() {
        cout << "turn on\n";
    }
};
 
class TurnoffCommand : public Command {
public:
    virtual void doit() {
        cout << "turn off\n";
    }
};
 
class PrintCommand : public Command {
public:
    virtual void doit() {
        cout << "print\n";
    }
};

//和Command模式比较会发现,Sensor类的代码是完全一样的
class Sensor {
public:
    Sensor(Command* c) : command(c) {}
    void sense() {
    if (condition)
        command->doit();
    }
private:
    bool condition = true;
    Command* command;
};
 
 
int main() {
    TurnonCommand turnOn = TurnonCommand();
    PrintCommand print = PrintCommand();
    TurnoffCommand turnOff = TurnoffCommand();
    CompositeCommand commands = CompositeCommand();
    commands.add(&turnOn);
    commands.add(&print);
    commands.add(&turnOff);
    Sensor s = Sensor(&commands);//需要更改这个Sensor执行的命令时,
                                 //只需要再初始化一个Command的derived class,
                                 //然后添加到commands里就可以了,
                                 //不需要更改Sensor的代码
    s.sense();
    return 0;
}

Features Composite mode

The relation "one to many" (such as a plurality of Sensor and Command) to the conversion relation "one to one" (a Sensor and a CompositeCommand, CompositeCommand class maintains a list of elements as in Command *) such that the code easier to maintain, in line with OCP.

However, this model also has limitations: Composite class must treat all elements of the list in the same way. For example, we now hold a list of objects and search for staff wages of employees today in the list, then do not treat all employees the same way (some wages and some do not send), and therefore not suitable for use Composite mode "a multi "to" one to one. "

Guess you like

Origin www.cnblogs.com/saltedreed/p/11884295.html