命令模式

  1. 它容易设计一个命令队列;
  2. 在需要的情况下,可容易记入日志;
  3. 允许接收请求的一方决定是否要否决请求;
  4. 容易实现对请求的撤销和重做;
  5. 由于加入新的具体命令类不影响其它类,因此增加新的会很容易.

命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分割开.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package order;

/**
* Created by hero on 17-2-20.
*/
public class Chef {

public void bakeMutton() {
System.out.println("烤羊肉");
}

public void bakeBeef() {
System.out.println("烤牛肉");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package order;

/**
* Created by hero on 17-2-20.
*/
public abstract class Order {
protected Chef chef;

public Order(Chef chef) {
this.chef = chef;
}

public abstract void execute();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package order;

/**
* Created by hero on 17-2-20.
*/
public class BakeBeef extends Order {
public BakeBeef(Chef chef) {
super(chef);
}

@Override
public void execute() {
chef.bakeBeef();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package order;

/**
* Created by hero on 17-2-20.
*/
public class BakeMutton extends Order {
public BakeMutton(Chef chef) {
super(chef);
}

@Override
public void execute() {
chef.bakeMutton();
}
}

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
package order;

import java.util.LinkedList;
import java.util.List;

/**
* Created by hero on 17-2-20.
*/
public class Waitress {
private List<Order> menu = new LinkedList<>();

public void receive(Order order) {
menu.add(order);
}

public void cancel(Order order) {
menu.remove(order);
}

public void transmit() {
for (Order order : menu) {
order.execute();
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package order;

/**
* Created by hero on 17-2-20.
*/
public class Main {
public static void main(String[] args) {
Chef chef = new Chef();
Waitress waitress = new Waitress();
Order beef = new BakeBeef(chef);
Order mutton = new BakeMutton(chef);

waitress.receive(beef);
waitress.receive(mutton);

waitress.transmit();
}
}