0%

设计模式-命令模式

请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令

命令模式

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接受者
class Receiver
{
public void Action()
{
Console.WriteLine("执行请求");
}
}
//Command 执行操作的接口
abstract class Command
{
protected Receiver receiver;
public Command(Receiver receiver)
{
this.receiver = receiver;
}
public abstract void Execute();
}
//ConcreateCommand 将一个接受者对象绑定于一个动作,调用接受者相应的操作,以实现Execute
class ConcreateCommand : Command
{
public ConcreateCommand(Receiver receiver) : base(receiver)
{}
public override void Execute()
{
receiver.Action();
}
}
//Invoker 要求命令执行请求
class Invoker
{
private Command command;
public void SetCommand(Command command)
{
this.command = command;
}
public void ExecuteCommand()
{
command.Execute();
}
}
//Client
Receiver rec = new Receiver();
Command co = new ConcreateCommand(rec);
Invoker i = new Invoker();

i.SetCommand(co);
i.ExecuteCommand();
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//命令接口
public interface Order {
void execute();
}
//请求类
public class Stock {

private String name = "ABC";
private int quantity = 10;

public void buy(){
System.out.println("Stock [ Name: "+name+",
Quantity: " + quantity +" ] bought");
}
public void sell(){
System.out.println("Stock [ Name: "+name+",
Quantity: " + quantity +" ] sold");
}
}
//实现命令接口
public class BuyStock implements Order {
private Stock abcStock;

public BuyStock(Stock abcStock){
this.abcStock = abcStock;
}

public void execute() {
abcStock.buy();
}
}
public class SellStock implements Order {
private Stock abcStock;

public SellStock(Stock abcStock){
this.abcStock = abcStock;
}

public void execute() {
abcStock.sell();
}
}
//命令调用类
import java.util.ArrayList;
import java.util.List;

public class Broker {
private List<Order> orderList = new ArrayList<Order>();

public void takeOrder(Order order){
orderList.add(order);
}

public void placeOrders(){
for (Order order : orderList) {
order.execute();
}
orderList.clear();
}
}
//Client
public class CommandPatternDemo {
public static void main(String[] args) {
Stock abcStock = new Stock();

BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);

Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);

broker.placeOrders();
}
}
/*
Stock [ Name: ABC, Quantity: 10 ] bought
Stock [ Name: ABC, Quantity: 10 ] sold
*/