iT邦幫忙

2023 iThome 鐵人賽

DAY 18
0
自我挑戰組

設計模式系列 第 18

Day18 - 命令模式(Command pattern)

  • 分享至 

  • xImage
  •  

介紹
命令模式將請求封裝為物件,透過不同的請求可對客戶進行參數化。

C++範例

#include <iostream>
using namespace std;

class Command
{
public:
    virtual void execute() = 0;
};

class Light
{
public:
    Light() {}

    void turnOn()
    {
        cout << "The light is on" << endl;
    }
    void turnOff()
    {
        cout << "The light is off" << endl;
    }
};

class FlipUpCommand : public Command
{
public:
    FlipUpCommand(Light &light) : theLight(light)
    {
    }

    virtual void execute()
    {
        theLight.turnOn();
    }

private:
    Light &theLight;
};

class FlipDownCommand : public Command
{
public:
    FlipDownCommand(Light &light) : theLight(light)
    {
    }
    virtual void execute()
    {
        theLight.turnOff();
    }

private:
    Light &theLight;
};

class Switch
{
public:
    Switch(Command &flipUpCmd, Command &flipDownCmd) :
        flipUpCommand(flipUpCmd),
        flipDownCommand(flipDownCmd)
    {
    }

    void flipUp()
    {
        flipUpCommand.execute();
    }

    void flipDown()
    {
        flipDownCommand.execute();
    }

private:
    Command &flipUpCommand;
    Command &flipDownCommand;
};

int main()
{
    Light lamp;
    FlipUpCommand switchUp(lamp);
    FlipDownCommand switchDown(lamp);

    Switch s(switchUp, switchDown);
    s.flipUp();
    s.flipDown();
}

Output:

The light is on
The light is off

Ref:
https://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Design_Patterns#Command


上一篇
Day17 - 狀態模式(State pattern)
下一篇
Day19 - 解釋器模式(Interpret pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言