設計模式之——命令模式

command.h

#ifndef COMMAND_H
#define COMMAND_H

#include "receiver.h"

class Command
{
public:
    Command(Receiver *receiver)
    {
        m_receiver = receiver;
    }
    virtual void execute(){}
protected:
    Receiver *m_receiver;
};

class ConcreteCommand : public Command
{
public:
    ConcreteCommand(Receiver *receiver):Command(receiver) {}
    void execute(){ m_receiver->action(); }
};

#endif // COMMAND_H

invoker.h

#ifndef INVOKER_H
#define INVOKER_H

#include "command.h"

class Invoker
{
public:
    Invoker() {}
    void setCommand(Command *command)
    {
        m_command = command;
    }

    void executeCommand()
    {
        m_command->execute();
    }

private:
    Command *m_command;
};


#endif // INVOKER_H

receiver.h

#ifndef RECEIVER_H
#define RECEIVER_H

#include <QtDebug>

class Receiver
{
public:
    Receiver() {}
    void action()
    {
        qDebug() << "執行請求";
    }
};

#endif // RECEIVER_H

UML
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章