命令
1:概述
在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,可以实现二者之间的松耦合。这就是本文要说的Command模式。
2:意图
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。[GOF 《设计模式》]
3:类图
4:代码
namespace Bll.Command
{
public class Document
{
}
public abstract class DocumentCommand
{
public Document _doc;
public DocumentCommand(Document doc)
{
this._doc = doc;
}
public abstract void Execute();
}
public class Write : DocumentCommand
{
public Write(Document doc)
: base(doc)
{ }
public override void Execute()
{ }
}
public class Delete:DocumentCommand
{
public Delete(Document doc)
: base(doc)
{ }
public override void Execute()
{ }
}
public class DocumentInvoker
{
Write _write;
Delete _del;
public DocumentInvoker(Write write, Delete del)
{
this._write = write;
this._del = del;
}
public void Wrie()
{
_write.Execute();
}
public void Del()
{
_del.Execute();
}
}
}
//调用
Document doc = new Document();
Write write = new Write(doc);
Delete del = new Delete(doc);
DocumentInvoker invoker = new DocumentInvoker(write, del);
invoker.Wrie();
invoker.Del();
{
public class Document
{
}
public abstract class DocumentCommand
{
public Document _doc;
public DocumentCommand(Document doc)
{
this._doc = doc;
}
public abstract void Execute();
}
public class Write : DocumentCommand
{
public Write(Document doc)
: base(doc)
{ }
public override void Execute()
{ }
}
public class Delete:DocumentCommand
{
public Delete(Document doc)
: base(doc)
{ }
public override void Execute()
{ }
}
public class DocumentInvoker
{
Write _write;
Delete _del;
public DocumentInvoker(Write write, Delete del)
{
this._write = write;
this._del = del;
}
public void Wrie()
{
_write.Execute();
}
public void Del()
{
_del.Execute();
}
}
}
//调用
Document doc = new Document();
Write write = new Write(doc);
Delete del = new Delete(doc);
DocumentInvoker invoker = new DocumentInvoker(write, del);
invoker.Wrie();
invoker.Del();