命令模式:
把需求的请求者和需求的执行者从对象中解耦出来,我个人的理解是把请求者和执行者分离,执行者封装复杂的执行过程,通过请求者的指示找到不同的执行者来处理或者执行不同的过程。
以下以命令者 命令传递者 命令执行者为例,解释妈妈喊起床的过程:
1
/// <summary>
2
/// 命令者
3
/// </summary>
4
public interface ICommand
5
{
6
void SetCommand(IOrder order);
7
void Press();
8
}
9![]()
10
/// <summary>
11
/// 命令接受者
12
/// </summary>
13
public interface IOrder
14
{
15
void AddOrder(IAction action);
16
void ShowAction();
17
}
18![]()
19
/// <summary>
20
/// 命令内容处理者
21
/// </summary>
22
public interface IAction
23
{
24
void Action();
25
}
26![]()
27
public class Commmander : ICommand
28
{
29
private IOrder order;
30![]()
31
ICommand Members
48
}
49![]()
50
public class Order : IOrder
51
{
52
private List<IAction> actions=new List<IAction>();
53![]()
54
IOrder Members
71
}
72![]()
73
命令操作
124![]()
125
class Program
126
{
127
static void Main(string[] args)
128
{
129
ICommand cmd = new Commmander();
130
//当然我在这里写的比较简单
131
//复杂的Order定制可以用到工厂模式
132
IOrder order = new Order();
133![]()
134
order.AddOrder(new Up());
135
order.AddOrder(new Toothbrushing());
136
order.AddOrder(new Wash());
137
order.AddOrder(new Out());
138
cmd.SetCommand(order);
139
cmd.Press();
140![]()
141
Console.Read();
142
}
143
}
/// <summary>2
/// 命令者3
/// </summary>4
public interface ICommand5
{6
void SetCommand(IOrder order);7
void Press();8
}9

10
/// <summary>11
/// 命令接受者12
/// </summary>13
public interface IOrder 14
{15
void AddOrder(IAction action);16
void ShowAction();17
}18

19
/// <summary>20
/// 命令内容处理者21
/// </summary>22
public interface IAction 23
{24
void Action();25
}26

27
public class Commmander : ICommand28
{29
private IOrder order;30

31
ICommand Members48
}49

50
public class Order : IOrder51
{52
private List<IAction> actions=new List<IAction>();53

54
IOrder Members71
}72

73
命令操作124

125
class Program126
{127
static void Main(string[] args)128
{129
ICommand cmd = new Commmander();130
//当然我在这里写的比较简单131
//复杂的Order定制可以用到工厂模式132
IOrder order = new Order();133

134
order.AddOrder(new Up());135
order.AddOrder(new Toothbrushing());136
order.AddOrder(new Wash());137
order.AddOrder(new Out());138
cmd.SetCommand(order);139
cmd.Press();140

141
Console.Read();142
}143
}

浙公网安备 33010602011771号