人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

May 28, 2006

设计模式纵横谈(15)Command 命令模式

Filed under: Design Pattern

隔离 行为请求者 和 行为实现者 之间的耦合.
将行为抽象成object.
行为的请求者传递一个对象,该对象表达了一个方法(行为)

//== Version 1.
class Application
{
    public void Show()
    {
        Document doc = new Document();
        doc.ShowText();
       
        Graphics graph = new Graphics();
        graph.ShowGraphics();
    }
       
}

class Document
{
    public void ShowText()
    {
        …
    }
}

class Graphics
{
    public ShowGraphics()
    {
        …
    }
}

此时,Application 直接依赖于 document 和 graphics的showXX()这样的
具体行为实现.
考虑如何实现undo,redo,需要添加大量的代码.

//== Version 2.
public interface Command
{
    public void Show();
    public void Undo();
    public void Redo();
}

//==这个设计违背了单一职责原理,
class Document : Command
{
    public virtual void Show()
    {
   
    }
}

class Graphics : Command
{
    public virtual void Show()
    {
   
    }
}

class Application
{
    Stack<Command> commands;
    Stack<Command> undoList;
   
    public void Show()
    {
        foreach(Command c in list)
        {
            c.Show();
        }
    }
   
    public void Undo()
    {
        if(canUndo)
        {
            Command command = commands.Pop();
            command.Undo();
            undoList.Push(command);
        }
    }
   
    public void Redo()
    {
        if(canUndo)
        {
            Command command = undoList.Pop();
            command.Redo();
        }
    }       
}

//== Version 3.  扩展已有的类
//已存在,实现细节
class Document : Command
{
    public virtual void Show()
    {
   
    }
}

class Graphics : Command
{
    public virtual void Show()
    {
   
    }
}

//==实现command 模式
public interface Command
{
    public void Show();
    public void Undo();
    public void Redo();
}

//==具体化的行为对象,
class DocumentCommand : Command
{
    Document doc;
   
    public DocumentCommand(Document doc)
    {
        this.doc = doc;
    }
   
    public void Show()
    {
        doc.ShowText()
    }
   
    public void Undo()
    {
        …
    }
   
    public void Redo()
    {
        …
    }
}

此时,Application不再依赖于document和graphics这样的细节, 而是依赖于Command这样的
抽象,体现了依赖导致原则.

Command和Delegate之间的选择:

Command更趋向于oo的特征,更符合抽象的原则. Delegate 更灵活

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/05/28/p67/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham