Command(命令模式——行为模型)

在这里插入图片描述
A——>B【A调用B】 将B抽象为对象
Command模式【应用范围较小】
动机

在这里插入图片描述
意图
在这里插入图片描述
结构
在这里插入图片描述
代码
Version01

class Document
{
    public void ShowText()
    {
        //....
    }
}
class Graphics
{
    public void ShowGraphics()
    {
        //....
    }
}
//应用程序主干/高层抽象
public class Application
{
    public void Show()
    {
        Document doc = new Document();
        doc.ShowText();//直接依赖具体行为实现

        Graphics gra = new Graphics();
        gra.ShowGraphics();//直接依赖具体行为实现
    }
}

改进Version2

//已经存在的类,实现细节,底层实现
class Document
{
    public void ShowText()
    {
        //....
    }
}
//实现Command的设计模式——抽象体
interface Command
{
    void Show();
    void Undo();
    void Redo();
}
//具体化命令对象——从抽象意义来讲,DocumentCommand表示一个行为
class DocumentCommand : Command
{
    private Document doc;
    public DocumentCommand(Document doc)
    {
        this.doc = doc;
    }
    public void Show()
    {
        doc.ShowText();
    }
    public void Undo()
    {        
    }
    public void Redo()
    {
    }
}
//应用程序主干/高层抽象 依赖抽象Command
class Application1
{
    Stack<Commanded> stack;
    public void Show()
    {
        foreach (Commanded c in stack)
        {
            c.Execute();
        }
    }
    public void Undo()
    {
        if (canUndo)
        {
            Commanded commanded = stack.Pop();
            commanded.Undo();
            undoList.Add(commanded);
        }
    }
    public void Redo()
    {
        if (canRedo)
        {
            Commanded commanded = undoList.Pop();
            commanded.Redo();
        }
    }
}

要点
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值