c++编程题之空调遥控器

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
class Light //电灯类
{
public:
    void turnLight(int degree){
        //调整灯光亮度,0表示关灯,100表示亮度最大
    }
};

class TV //电视机类
{
public:
    void setChannel(int channel){ //调整电视频道
        //0表示关机
        //1表示开机并切换到1频道
    }
};

class Command //抽象命令类
{
public:
    virtual void on()=0;
    virtual void off()=0;
};

class RemoteController
{
protected:
    Command *commands[4];//四个遥控器按钮
public:
    void onPressButton(int button)
    {
        if (button%2 == 0)
        {
            commands[button]->on();
        }
        else
        {
            commands[button]->off();
        }
    }
    void setCommand(int button, Command *command)
    {
        commands[button] = command;
    }
};

class LightCommand : public Command
{
protected:
    Light *light;
public:
    LightCommand(Light *light){this->light = light;}
    void on(){light->turnLight(100);}
    void off(){light->turnLight(0);}
};

class TVCommand : public Command
{
protected:
    TV *tv;
public:
    TVCommand(TV *tv){this->tv = tv;}
    void on(){tv->setChannel(1);}
    void off(){tv->setChannel(0);}
};

int main(int argc, char const *argv[])
{
    Light light;
    TV tv;
    LightCommand lightCommand(&light);
    TVCommand tvCommand(&tv);
    RemoteController remoteController;
    remoteController.setCommand(0, &lightCommand);
    remoteController.setCommand(1, &lightCommand);
    remoteController.setCommand(2, &tvCommand);
    remoteController.setCommand(3, &tvCommand);

    return 0;
}

posted @ 2020-08-21 15:26  Chilk  阅读(491)  评论(0编辑  收藏  举报