设计模式之命令模式

本文介绍了解耦命令执行者与调用者的观察者模式,并通过一个C++实例详细展示了该模式的应用场景,包括Invoker、Receiver及具体命令的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

观察者模式(command)属于行为模式,用于解除命令的执行者和命令的调用者之间的耦合关系,例如,餐馆的厨师就是命令的执行者,他能够做各种菜,也就是能执行各种命令,而点菜的顾客并不需要知道是哪个厨师炒哪个菜。
下面是观察者模式的C++实现,代码可到本人github网页下载:设计模式例子

/*
 * Example of 'Command' design pattern.
 * Copyright (C) 2016 Leo Wang 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <vector>
using namespace std;

class CReceiver
{
public:
    void DoFunctionA()
    {
        cout<<"Do function A!"<<endl;
    };

    void DoFunctionB()
    {
        cout<<"Do function B!"<<endl;
    };
};

class CCommand
{
public:
    CReceiver* cp_receiver;
public:
    virtual void Do(){};
public:
    CCommand(CReceiver* c_receiver)
    {
        cp_receiver=c_receiver;
    };
};

class CConcreteCommandA:public CCommand
{
public:
    void Do()
    {
        cp_receiver->DoFunctionA();
    };
public:
    CConcreteCommandA(CReceiver* c_receiver):CCommand(c_receiver){};
};

class CConcreteCommandB:public CCommand
{
public:
    void Do()
    {
        cp_receiver->DoFunctionB();
    };
public:
    CConcreteCommandB(CReceiver* c_receiver):CCommand(c_receiver){};
};

class CInvoker
{
public:
    vector<CCommand*> v_cmd;
public:
    void AddCommand(CCommand* p_cmd)
    {
        v_cmd.push_back(p_cmd);
    };

    void Execute()
    {
        vector<CCommand*>::iterator it;
        it=v_cmd.begin();
        for(;it!=v_cmd.end();it++)
        {
            (*it)->Do();
        };
    };
};

void main()
{
    CInvoker* cp_invoker=new CInvoker();
    CReceiver* cp_receiver=new CReceiver();
    CCommand* cp_command;
    cp_command=new CConcreteCommandA(cp_receiver);
    cp_invoker->AddCommand(cp_command);
    cp_command=new CConcreteCommandB(cp_receiver);
    cp_invoker->AddCommand(cp_command);
    cp_invoker->Execute();
};

前面举的例子中:
厨师对应的就是Invoker,服务员对应的就是Receiver,客人就是客户端调用程序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值