File tree Expand file tree Collapse file tree
src/designpattern/command Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package designpattern .command ;
2+
3+ import java .util .List ;
4+
5+ /**
6+ * 用来声明执行操作的接口
7+ *
8+ * @author liu yuning
9+ *
10+ */
11+ public abstract class Command {
12+
13+ protected List <Reciever > recievers ;
14+
15+ public Command (List <Reciever > recievers ) {
16+ this .recievers = recievers ;
17+ }
18+
19+ public void addRecievers (Reciever reciever ) {
20+ this .recievers .add (reciever );
21+ }
22+
23+ public abstract void execute ();
24+
25+ }
26+
27+ // 将一个接收者对象绑定于一个动作,调用接收者相应的操作,以实现execute
28+ class ConcreteCommand extends Command {
29+
30+ public ConcreteCommand (List <Reciever > recievers ) {
31+ super (recievers );
32+ }
33+
34+ @ Override
35+ public void execute () {
36+ for (Reciever reciever : recievers ) {
37+ reciever .action ();
38+ }
39+ }
40+
41+ }
Original file line number Diff line number Diff line change 1+ package designpattern .command ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
6+ /**
7+ * 创建一个具体命令对象并设定它的接收者
8+ *
9+ * @author liu yuning
10+ *
11+ */
12+ public class CommandClient {
13+
14+ public static void main (String [] args ) {
15+ List <Reciever > recievers = new ArrayList <Reciever >();
16+
17+ recievers .add (new RecieverA ());
18+ recievers .add (new RecieverB ());
19+ recievers .add (new RecieverC ());
20+
21+ Command command = new ConcreteCommand (recievers );
22+ Invoker invoker = new Invoker ();
23+
24+ invoker .setCommand (command );
25+ invoker .executeCommand ();
26+
27+ }
28+
29+ }
Original file line number Diff line number Diff line change 1+ package designpattern .command ;
2+
3+ /**
4+ * 要求该命令执行这个请求
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class Invoker {
10+
11+ private Command command ;
12+
13+ public void setCommand (Command command ) {
14+ this .command = command ;
15+ }
16+
17+ public void executeCommand () {
18+ command .execute ();
19+ }
20+
21+ }
Original file line number Diff line number Diff line change 1+ package designpattern .command ;
2+
3+ /**
4+ * 知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接收者。真正执行请求的地方!
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ interface Reciever {
10+ public void action ();
11+ }
12+
13+ class RecieverA implements Reciever {
14+
15+ @ Override
16+ public void action () {
17+ System .out .println ("RecieverA执行请求!" );
18+ }
19+
20+ }
21+
22+ class RecieverB implements Reciever {
23+
24+ @ Override
25+ public void action () {
26+ System .out .println ("RecieverB执行请求!" );
27+ }
28+ }
29+
30+ class RecieverC implements Reciever {
31+
32+ @ Override
33+ public void action () {
34+ System .out .println ("RecieverC执行请求!" );
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments