command pattern -- 命令模式

在软件构建过程中,行为请求者行为实现者通常呈现一种紧耦合。但在某些场合,比如需要对行为进行记录、撤销/重做(undo/redo)、事务等处理,这种无法抵御变化的紧耦合是不合适的。Command设计模式就是在这种情况下,将行为请求者行为实现者解耦,将一组行为抽象为对象,以实现二者之间的松耦合。


“Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.” – GoF

将一个请求封装为一个对象,从而可用不同的请求(一个被封装成了对象的请求)对客户程序(即调用者)进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。


实例分析,实际工作中,我们遇到了很多文档,都支持回退/前进的功能,它们快捷键也是惊人的相似Ctrl+z与Ctrl+y。下面将用一段代码来实现其操作,其原理就是命令模式。

#include <iostream>
#include <stack>

class Receiver
{
    private:
        std::string str;
    public:
        std::string get_str(){ return str; }
        void set_str(const std::string& s){ str=s; }
        void append(std::string astr){ str.append(astr); }
        void show(){ std::cout<<str<<std::endl; }
};

class Command
{
    public:
        virtual void execute()=0;
        Command(Receiver *re,const std::string& p)
        :r(re),par(p)
        {}
        virtual ~Command(){}
    protected:
        Receiver * r;
        std::string par;
};

class UndoCommand:public Command
{
    public:
        UndoCommand(Receiver *re,const std::string& p)
        :Command(re,p)
        {}
        virtual void undo()=0;
        virtual void redo()=0;
        virtual ~UndoCommand(){}
};

class ConcreteCommand:public UndoCommand
{
    public:
        ConcreteCommand(Receiver *re,const std::string& p)
        :UndoCommand(re,p)
        {}
        void execute()
        {
            preStr=r->get_str();
            r->append(par);
            curStr=r->get_str();
        }

        void undo()
        {
            r->set_str(preStr);
        }

        void redo()
        {
            r->set_str(curStr);
        }
    private:
        std::string preStr;
        std::string curStr;
        
}; 

class ConcreteManager
{
    private:
        std::stack<Command*> exeComStack;
        std::stack<Command*> undoComStack;
    public:
        void executeCommand(Command* cmd);
        void undoCommand();
        void redoCommand();
        ~ConcreteManager();
};
ConcreteManager::~ConcreteManager()
{
    while(exeComStack.size()>0)
    {
        delete exeComStack.top();
        exeComStack.pop();
    }
    while(undoComStack.size()>0)
    {
        delete undoComStack.top();
        undoComStack.pop();
    }
}

void ConcreteManager::executeCommand(Command* cmd)
{
    cmd->execute();
    exeComStack.push(cmd);
}

void ConcreteManager::undoCommand()
{
    if(exeComStack.size()>0)
    {
        UndoCommand *cmd =dynamic_cast<UndoCommand*>(exeComStack.top());
        exeComStack.pop();
        cmd->undo();
        undoComStack.push(cmd);
    }
}

void ConcreteManager::redoCommand()
{
    if(undoComStack.size()>0)
    {
        UndoCommand * cmd=dynamic_cast<UndoCommand*>(undoComStack.top());
        undoComStack.pop();
        cmd->redo();
        exeComStack.push(cmd);
    }
}

int main(int argc,char** argv)
{
    ConcreteManager *co=new ConcreteManager;
    Receiver* re=new Receiver;
    Command* cm1=new ConcreteCommand(re,"hu");
    Command* cm2=new ConcreteCommand(re,"cs");
    Command* cm3=new ConcreteCommand(re,"dn");
    Command* cm4=new ConcreteCommand(re,"!!"); 
    co->executeCommand(cm1);
    co->executeCommand(cm2);
    co->executeCommand(cm3);
    co->executeCommand(cm4);
    re->show();
    co->undoCommand();
    co->undoCommand();
    co->undoCommand();
    re->show();
    co->redoCommand();
    co->redoCommand();
    co->redoCommand();
    co->redoCommand();
    re->show();
    delete re;
    delete co;
    return 0;
}


运行结果


singleton pattern--单件模式
factory mothed pattern--工厂方法模式
abstract factory pattern--抽象工厂模式
builder pattern--建造者模式
prototype pattern--原型模式
adapter pattern--适配器模式
bridge pattern -- 桥接模式
composite pattern -- 组合模式
decorator pattern -- 装饰模式
decorator pattern -- 享元模式
decorator pattern -- 代理模式
decorator pattern -- 责任链模式
decorator pattern -- 命令模式

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java设计模式是一组经过实践验证的面向对象设计原则和模式,可以帮助开发人员解决常见的软件设计问题。下面是常见的23种设计模式: 1. 创建型模式(Creational Patterns): - 工厂方法模式(Factory Method Pattern) - 抽象工厂模式(Abstract Factory Pattern) - 单例模式(Singleton Pattern) - 原型模式(Prototype Pattern) - 建造者模式(Builder Pattern) 2. 结构型模式(Structural Patterns): - 适配器模式(Adapter Pattern) - 桥接模式(Bridge Pattern) - 组合模式(Composite Pattern) - 装饰器模式(Decorator Pattern) - 外观模式(Facade Pattern) - 享元模式(Flyweight Pattern) - 代理模式(Proxy Pattern) 3. 行为型模式(Behavioral Patterns): - 责任链模式(Chain of Responsibility Pattern) - 命令模式Command Pattern) - 解释器模式(Interpreter Pattern) - 迭代器模式(Iterator Pattern) - 中介者模式(Mediator Pattern) - 备忘录模式(Memento Pattern) - 观察者模式(Observer Pattern) - 状态模式(State Pattern) - 策略模式(Strategy Pattern) - 模板方法模式(Template Method Pattern) - 访问者模式(Visitor Pattern) 4. 并发型模式(Concurrency Patterns): - 保护性暂停模式(Guarded Suspension Pattern) - 生产者-消费者模式(Producer-Consumer Pattern) - 读写锁模式(Read-Write Lock Pattern) - 信号量模式(Semaphore Pattern) - 线程池模式(Thread Pool Pattern) 这些设计模式可以根据问题的特点和需求来选择使用,它们提供了一些可复用的解决方案,有助于开发高质量、可维护且易于扩展的软件系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值