IronMan之命令
在本篇中还是围绕着“IronMan”来讲,在上一篇“外观”中我们说到过“控制中心”。它是负责IronMan的核心,所有能想象到的功能都跟它有关系,
就在使用它的时候,发现了一些问题,比如使用它来命令部件做一些操作:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
1
/// <summary>
2
/// 控制中心
3
/// </summary>
4
public
class
CenterController
5 {
6
public
void
Attact()
7 {
8 ComponteCase comCase =
new
ComponteCase();
9 comCase.Attact();
10 }
11 }
12
/// <summary>
13
/// 部件
14
/// </summary>
15
public
class
ComponteCase
16 {
17
public
void
Attact()
18 {
19 Console.WriteLine(
"示例部件攻击1"
);
20 }
21 }
|
从
从上面的“控制中心”中可以看出,它是直接使用的部件,如果这时候要添加、修改或者删除部件的攻击方式,那么“控制中心”也要跟着做出修改。 耦合度很大,那怎么样要使“控制中心”和“部件”之间变得是松耦合呢?
命令模式的定义:将一组行为抽象为对象,实现二者之间的松耦合。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
1
/// <summary>
2
/// 抽象命令
3
/// </summary>
4
public
abstract
class
Command
5 {
6
public
abstract
void
Execute();
7 }
8
/// <summary>
9
/// 具体命令类(示例部件攻击命令)
10
/// </summary>
11
public
class
RealizeCommand : Command
12 {
13
private
ComponteCase compontecase =
new
ComponteCase();
14
public
override
void
Execute()
15 {
16
//业务操作等等
17 compontecase.Attact();
18 }
19 }
|
添加了抽象命令类和具体命令类,具体命令类已经代表了一个命令,就是示例部件攻击:
|
1
2
|
1 CenterController centercontroller =
new
CenterController(
new
RealizeCommand());
2 centercontroller.Attact();
|
也可以再新建其它的具体命令类,引用其它部件,使用其攻击方法,这样便实现了动态注入,把控制中心和部件
从紧耦合状态改变到了松耦合。
这里会有人有疑问了,如果要执行多个命令怎么办?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
1
/// <summary>
2
/// 命令板
3
/// </summary>
4
public
class
CommandList
5 {
6
private
List<Command> commands =
new
List<Command>();
7
public
CommandList() { }
8
public
CommandList(Command command)
//动态注入
9 {
10 commands.Add(command);
11 }
12
public
void
AddCommand(Command command)
13 {
14 commands.Add(command);
15 }
16
public
void
RemoveCommand(Command command)
17 {
18 commands.Remove(command);
19 }
20
public
void
Execute()
21 {
22
foreach
(Command command
in
commands)
23 {
24 command.Execute();
25 }
26 }
27 }
|
添加一个命令板类,再修改一下控制中心,使得“控制中心”和“抽象命令”间都进行消耦,下面再看一下修改后的“控制中心”:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
1
/// <summary>
2
/// 命令板
3
/// </summary>
4
public
class
CommandList
5 {
6
private
List<Command> commands =
new
List<Command>();
7
public
CommandList() { }
8
public
CommandList(Command command)
//动态注入
9 {
10 commands.Add(command);
11 }
12
public
void
AddCommand(Command command)
13 {
14 commands.Add(command);
15 }
16
public
void
RemoveCommand(Command command)
17 {
18 commands.Remove(command);
19 }
20
public
void
Execute()
21 {
22
foreach
(Command command
in
commands)
23 {
24 command.Execute();
25 }
26 }
27 }
|
使用的方式还是和上一个方式相同,只是上个方式是把命令动态注入,现在修改成了把命令板动态注入。
命令模式就到这里了。。END
下一篇实现更佳的可扩展的命令模式
本文转自jinyuan0829 51CTO博客,原文链接:http://blog.51cto.com/jinyuan/1409417,如需转载请自行联系原作者