命令模式是一种行为型模式,应用比较狭窄,当你需要对某一系列的方法调用实现解耦,(注:一般的方法调用方法,是直接通过对象调用或者类调用,这样的调用方式,行为请求者和行为实现者之间的是紧耦合的关系即 A和B的调用关系)比如你需要对系列的动作调用实现记录,撤销,重做等操作的时候,就需要对这些行为请求者和行为实现者之间实现解耦。那么command模式给你一个思路:抽象,引入第三者,实现解耦。这也是许多设计模式的一个比较通行的解耦思路。在这个模式中间,你需要思考的是你要 让行为请求者(A)和行为实现者(B)之间的关系是紧耦合的,你要解耦,那么你可以在他们之间引入第三者C,C是用来干嘛的呢?C是对行为实现者B系列的抽象,那么,现在可以让A与C来联系,而B也与C来联系,这样,具体的行为请求者和行为实现者之间他们就以来于抽象的C,即:具体依赖抽象。在示例代码中,Invoker就是行为请求者,Command就是抽象出来的接口。ConcreateCommand就是具体的行为实现者。Reciever就是原始的行为包含者。下面来看代码实现
public class Brush
{
public void ShowBrush()
{
Console.WriteLine("Using Brush...");
}
}
public class Pen
{
public void ShowPen()
{
Console.WriteLine("Using Pencil...");
}
}
public class Pencil
{
public void ShowPencil()
{
Console.WriteLine("Using Pencil...");
}
}
public class InvokerDraw
{
public void Draw()
{
Brush brush = new Brush();
brush.ShowBrush();
Pen pen = new Pen();
pen.ShowPen();
Pencil pencil = new Pencil();
pencil.ShowPencil();
}
static void Main()
{
InvokerDraw i = new InvokerDraw();
i.Draw();
}
}
}
上面的代码是分别使用Brush Pen Pencil 进行一个Draw的操作。但是如果你想对这些操作进行某些控制,比如重做,撤销,那么:
namespace Command_DesignPattern
{
public interface Command
{
void Show();
void Redo();
void undo();
}
public class Brush
{
public void ShowBrush()
{
Console.WriteLine("Using Brush...");
}
}
public class Pen
{
public void ShowPen()
{
Console.WriteLine("Using Pencil...");
}
}
public class Pencil
{
public void ShowPencil()
{
Console.WriteLine("Using Pencil...");
}
}
public class BrushCommand:Command
{
#region Command 成员
public void Show()
{
Console.WriteLine("Using command Brush ...");
}
public void Redo()
{
Console.WriteLine("Using Redo command Brush...");
}
public void undo()
{
Console.WriteLine("Using Undo command Brush...");
}
#endregion
}
public class PenCommand : Command
{
#region Command 成员
public void Show()
{
Console.WriteLine("Using command Pen ...");
}
public void Redo()
{
Console.WriteLine("Using Redo command Pen...");
}
public void undo()
{
Console.WriteLine("Using Undo command Pen...");
}
#endregion
}
public class PencilCommand : Command
{
#region Command 成员
public void Show()
{
Console.WriteLine("Using command Pencil ...");
}
public void Redo()
{
Console.WriteLine("Using Redo command Pencil...");
}
public void undo()
{
Console.WriteLine("Using Undo command Pencil...");
}
#endregion
}
public class InvokerDraw
{
public void Draw()
{
Brush brush = new Brush();
brush.ShowBrush();
Pen pen = new Pen();
pen.ShowPen();
Pencil pencil = new Pencil();
pencil.ShowPencil();
}
public void CommandDraw()
{
BrushCommand brush = new BrushCommand();
brush.Show();
PenCommand pen = new PenCommand();
pen.Show();
PencilCommand pencil = new PencilCommand();
pencil.Show();
}
static void Main()
{
InvokerDraw i = new InvokerDraw();
i.Draw();
i.CommandDraw();
//also you can do redo undo operations ....
}
}
}