c++实现设计模式中的命令模式,输出结果不正确.该如何解决
c++实现设计模式中的命令模式,输出结果不正确.
为什么输出结果是两个kttchen light is off.应该是kitchen light is on和kitchen light is off啊.
------解决方案--------------------
on/off commands 需要分配内存才能够使用,比如。
别忘了,delete []。
用 std::vector 更好。
#include<iostream>
#include<string>
using namespace std;
class Light{
public:
Light(string s);
void on();
void off();
protected:
string concretelight;
};
class Command{
public:
virtual void execute(){};
};
class noCommand:public Command
{
public:
void execute(){};
};
class LightOnCommand:public Command{
public:
LightOnCommand(Light &light);
void execute();
private:
Light *plighton;
};
class LightOffCommand:public Command{
public:
LightOffCommand(Light &light);
void execute();
private:
Light *plightoff;
};
class RemoteControl
{
public:
RemoteControl();
void setCommand(int slot,Command &onCommand,Command &offCommand);
void onButtonWasPressed(int slot);
void offButtonWasPressed(int slot);
private:
Command *onCommands[];
Command *offCommands[];
};
Light::Light(string s)
{
concretelight=s;
}
void Light::on(){
cout<<concretelight<<"light is on"<<endl;
}
void Light::off(){
cout<<concretelight<<"Light is off"<<endl;
}
LightOnCommand::LightOnCommand(Light &light){
plighton=&light;
}
void LightOnCommand::execute(){
plighton->on();
}
LightOffCommand::LightOffCommand(Light &light){
plightoff=&light;
}
void LightOffCommand::execute(){
plightoff->off();
}
RemoteControl::RemoteControl()
{
noCommand nocommand;
for(int i=0;i<1;i++)
{
onCommands[i]=&nocommand;
offCommands[i]=&nocommand;
}
}
void RemoteControl::setCommand(int slot,Command &onCommand,Command &offCommand)
{
onCommands[slot]=&onCommand;
offCommands[slot]=&offCommand;
}
void RemoteControl::onButtonWasPressed(int slot)
{
onCommands[slot]->execute();
}
void RemoteControl::offButtonWasPressed(int slot)
{
offCommands[slot]->execute();
}
int main(){
Light light("Kitchen");
RemoteControl remotecontrol;
LightOnCommand lighton=LightOnCommand(light);
LightOffCommand lightoff=LightOffCommand(light);
remotecontrol.setCommand(0,lighton,lightoff);
remotecontrol.onButtonWasPressed(0);
remotecontrol.offButtonWasPressed(0);
return 0;
}
为什么输出结果是两个kttchen light is off.应该是kitchen light is on和kitchen light is off啊.
------解决方案--------------------
RemoteControl::RemoteControl()
{
noCommand nocommand;
for(int i=0;i<1;i++)
{
onCommands[i]=&nocommand;
offCommands[i]=&nocommand;
}
}
on/off commands 需要分配内存才能够使用,比如。
onCommands = new Command [10];
别忘了,delete []。
用 std::vector 更好。