C#设计模式——命令模式(Command Pattern)
<p>一、概述<br />通常来说,“活动哀求者”与“活动实现者”是紧耦合的。但在某些场合,比如要对活动举行“记载、取消/重做、事务”等处置惩罚,这种无法反抗厘革的紧耦合是不符合的。在这些环境下,将“活动哀求者”与“活动实现者”解耦,实现二者之间的松耦合就至关重要。下令模式是管理这类标题的一个比力好的方法。<br />二、下令模式<br />下令模式将一个哀求封装为一个对象,从而使你可用差别的哀求对客户举行参数化;对哀求列队或记载哀求日志,以及支持可取消的操作。<br />下令模式的结构图如下<br /></p><p>Command界说了下令的接口<br />ConcreteCommand实现Command接口,界说了具体的下令<br />Client用于创建具体的下令并设定吸收者<br />Invoker要求Command实行相应的哀求<br />Receiver实行与实行一个哀求,任何一个类都大概作为Receiver。<br />三、示例<br />假定要实现一个画图体系,要求支持取消功能,下面就用下令模式来实现这一需求。<br />起首界说一个抽象的下令接口</p>
public interface IGraphCommand
{
void Draw();
void Undo();
}
<p>接着实现具体的画图下令</p>
public class Line : IGraphCommand
{
private Point startPoint;
private Point endPoint;
public Line(Point start, Point end)
{
startPoint = start;
endPoint = end;
}
public void Draw()
{
Console.WriteLine("Draw Line:{0} To {1}", startPoint.ToString(), endPoint.ToString());
}
public void Undo()
{
Console.WriteLine("Erase Line:{0} To {1}", startPoint.ToString(), endPoint.ToString());
}
}
public class Rectangle : IGraphCommand
{
private Point topLeftPoint;
private Point bottomRightPoint;
public Rectangle(Point topLeft, Point bottomRight)
{
topLeftPoint = topLeft;
bottomRightPoint = bottomRight;
}
public void Draw()
{
Console.WriteLine("Draw Rectangle: Top Left Point {0},Bottom Right Point {1}", topLeftPoint.ToString(), bottomRightPoint.ToString());
}
public void Undo()
{
Console.WriteLine("Erase Rectangle: Top Left Point {0},Bottom Right Point {1}", topLeftPoint.ToString(), bottomRightPoint.ToString());
}
}
public class Circle : IGraphCommand
{
private Point centerPoint;
private int radius;
public Circle(Point center, int radius)
{
centerPoint = center;
this.radius = radius;
}
public void Draw()
{
Console.WriteLine("Draw Circle: Center Point {0},Radius {1}", centerPoint.ToString(), radius.ToString());
}
publi cvoid Undo()
{
Console.WriteLine("Erase Circle: Center Point {0},Radius {1}", centerPoint.ToString(), radius.ToString());
}
}
<p>然后再界说画图类作为下令吸收者</p>
public class Graphics
{
Stack<IGraphCommand> commands =new Stack<IGraphCommand>();
public void Draw(IGraphCommand command)
{
command.Draw();
commands.Push(command);
}
public void Undo()
{
IGraphCommand command = commands.Pop();
command.Undo();
}
}
<p>末了看一下怎样调用</p>
static void Main(string[] args)
{
Line line =new Line(new Point(10, 10), new Point(100, 10));
Rectangle rectangle =new Rectangle(new Point(20, 20), new Point(50, 30));
Circle circle =new Circle(new Point(500, 500), 200);
Graphics graphics =new Graphics();
graphics.Draw(line);
graphics.Draw(rectangle);
graphics.Undo();
graphics.Draw(circle);
Console.ReadLine();
}
<p> </p>
页:
[1]