命令模式
命令模式(Command Pattern)是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
示例演示:
我们创建一个people实体,并提供两个方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package test.command;
public class People {
private Integer id = 1;
private String name = "1";
public void add() {
System.out.println("add id: " + id + " name:" + name);
}
public void remove() {
System.out.println("remove id: " + id + " name:" + name);
}
}新建一个order命令的接口
1
2
3
4
5package test.command;
public interface Order {
void execute();
}分别对people的add和remove方法创建order接口的实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14package test.command;
public class PeopleAdd implements Order {
private People people;
public PeopleAdd(People people) {
this.people = people;
}
public void execute() {
people.add();
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14package test.command;
public class PeopleRemove implements Order {
private People people;
public PeopleRemove(People people) {
this.people = people;
}
public void execute() {
people.remove();
}
}创建一个命令调用实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package test.command;
import java.util.ArrayList;
import java.util.List;
public class Broker {
private List<Order> orders = new ArrayList<>();
public void takeOrder(Order order) {
orders.add(order);
}
public void placeOrders() {
for (Order order : orders) {
order.execute();
}
orders.clear();
}
}完成上述步骤,我们就可以开始演示了
1
2
3
4
5
6
7
8
9
10
11
12
13
14package test.command;
public class CommandDemo {
public static void main(String[] args) {
People people = new People();
PeopleAdd peopleAdd = new PeopleAdd(people);
PeopleRemove peopleRemove = new PeopleRemove(people);
Broker broker = new Broker();
broker.takeOrder(peopleAdd);
broker.takeOrder(peopleRemove);
broker.placeOrders();
}
}运行结果:
1
2add id: 1name:1
remove id: 1name:1
说明:
优点: 1、降低了系统耦合度。 2、新的命令可以很容易添加到系统中去。
缺点:使用命令模式可能会导致某些系统有过多的具体命令类。