HeadFirst DesignPattern读书摘记(6)--命令模式
命令模式定义:将请求封装成对象,这可以让你使用不同的请求、队列,或者日志请求来参数化其他对象。命令模式也可以支持撤销。
学习命令模式的要点:
1、命令模式将发出请求的对象和执行请求的对象解耦。
2、在被解耦的两者之间是通过命令对象进行沟通的。命令对象封装了接受者和一个或者一组动作。
3、调用者通过调用命令对象的execute()发出命令,这会使得接受者的动作被调用。
4、调用者可以就收命令当作参数,甚至在运行时动态的进行。
5、命令可以支持撤销,做法是实现一个undo()方法来回到execute()被执行前的状态。
6、宏命令是命令的一种简单的延伸,允许调用多个命令。宏方法也可以支持撤销。
7、命令也可以用来实现日志和事务系统。
本章涉及的简单代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace 命令模式
{
public interface Command
{
string Execute();
}
//命令对象
public class LightOnCommand : Command
{
//负责接收请求的对象
Light light;
public LightOnCommand(Light light)
{
this.light = light;
}

Command 成员
}
public class LightOffCommand : Command
{
Light light;
public LightOffCommand(Light light)
{
this.light = light;
}
string Command.Execute()
{
return light.Off();
}
}
//命令接受者,负责具体命令的执行
public class Light
{
public string On()
{
return "Light is On!";
}
public string Off()
{
return "Light is Off!";
}
}
//调用则
public class SimpleRemoteControl
{
Command[] command=new Command[2];
public void SetCommond(Command onCommand,Command offComand)
{
this.command[0]= onCommand;
this.command[1] = offComand;
}
public string ButtonOnWasPressed()
{
return command[0].Execute();
}
public string ButtonOffWasPressed()
{
return command[1].Execute();
}
}
}
下一章预告:适配器模式和外观模式(随遇而安)
(注:记录一下这些内容只是以后查阅起来方便,作为自己知识积累的记录。其中有很多是参考网络上的资源,不再一一写出出处,还请原作者见谅。)


浙公网安备 33010602011771号