C#设计模式——命令模式(Command Pattern)

命令模式
命令模式将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。

示例
假定要实现一个绘图系统,要求支持撤销功能,下面就用命令模式来实现这一需求。
首先定义一个抽象的命令接口

 public interface IGraphCommand
 {
     void Draw();
     void Undo();
 }
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());
        }
    }

然后再定义绘图类作为命令接收者

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();
        }
    }

最后看一下如何调用

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();
    }

 

posted @ 2024-03-24 13:14  木狼  阅读(4)  评论(0编辑  收藏  举报