cpp
复制代码
#include <iostream>
class TV
{
private:
int currentChannel = 0;
public:
void changeChannel(int channel)
{
this->currentChannel = channel;
}
void turnOff()
{
std::cout << "TV is off." << std::endl;
}
void turnOn()
{
std::cout << "TV is on." << std::endl;
}
};
class Command
{
public:
virtual void execute() = 0;
};
class CommandOn : public Command
{
private:
TV* myTV;
public:
CommandOn(TV* tv)
{
myTV = tv;
}
void execute()
{
myTV->turnOn();
}
};
class CommandOff : public Command
{
private:
TV* myTV;
public:
CommandOff(TV* tv)
{
myTV = tv;
}
void execute()
{
myTV->turnOff();
}
};
class CommandChange : public Command
{
private:
TV* myTV;
int channel;
public:
CommandChange(TV* tv, int channel)
{
myTV = tv;
this->channel = channel;
}
void execute()
{
std::cout << "Switch Channel to " << channel << std::endl;
myTV->changeChannel(channel);
}
};
class Control
{
private:
Command* changChannel;
Command* offCommand;
Command* onCommand;
public:
Control(Command* changChannel, Command* off, Command* on)
{
this->changChannel = changChannel;
this->offCommand = off;
this->onCommand = on;
}
void changeChannel()
{
changChannel->execute();
}
void turnOff()
{
offCommand->execute();
}
void turnOn()
{
onCommand->execute();
}
};
int main()
{
TV* mytv = new TV();
Command* on = new CommandOn(mytv);
Command* off = new CommandOff(mytv);
Command* channel = new CommandChange(mytv, 3);
Control* control = new Control(channel, off, on);
control->turnOn();
control->changeChannel();
control->turnOff();
return 0;
}