主要目的是命令与接受者的解耦,使得程序的可扩展性增强
UML类图:
commamd 到 invoker 类之间应该是聚合的关系,上面没画对,懒得改了。
class lift
{
public:
lift(){};
~lift(){};
void up(void)
{
std::cout<<"lift go up!"<<std::endl;
}
void down(void)
{
std::cout<<"lift go down!"<<std::endl;
}
};
class command
{
public:
command(lift*plift):_lift(plift){};
~command(){};
virtual void behavior(void)=0;
lift* getLift(void) {return _lift;}
private:
lift*_lift;
};
class upCommand:public command
{
public:
upCommand(lift*plift):command(plift){};
~upCommand(){};
virtual void behavior(void)
{
getLift()->up();
}
};
class downCommand:public command
{
public:
downCommand(lift*plift):command(plift){};
~downCommand(){};
virtual void behavior(void)
{
getLift()->down();
}
};
class swcControl //invoke
{
public:
swcControl(command* cmd):_cmd(cmd)
{
}
~swcControl(){};
void action()
{
_cmd->behavior();
}
private:
command* _cmd;
};
void main()
{
lift*plift = new lift;
swcControl* m1 = new swcControl(new upCommand(plift));
swcControl* m2 = new swcControl(new downCommand(plift));
m1->action();
m2->action();
std::cin.get();
}