命令模式(Command Pattern)
命令模式(Command Pattern)是一种对象行为模式,分离了接受请求的对象与实现处理请求工作的对象,在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,将一组行为抽象为对象,实现二者之间的松耦合。这样,已经存在的类可以保持不变,使得增加新类的工作更简单。例如,很多软件的宏命令就提高了系统的自动化程度。命令模式还可以分离用户界面和业务对象,降低系统的耦合度。
using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApplication
{
//一般每个接口或类都写在单独的.cs文件中
//本示例为了执行查看方便才写在一起
public interface IGraphCommand
{
void Draw();
void Undo();
}
public struct Point
{
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
public int X { get; set; }
public int Y { get; set; }
}
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());
}
public void Undo()
{
Console.WriteLine("Erase Circle: Center Point {0}, Radius {1}", centerPoint.ToString(), radius.ToString());
}
}
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();
}
}
class Program
{
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(60, 30));
Circle circle = new Circle(new Point(600, 600), 200);
Graphics graphics = new Graphics();
graphics.Draw(line);
graphics.Draw(rectangle);
graphics.Undo();
graphics.Draw(circle);
Console.ReadKey();
}
}
}