Skip to content

Commit

Permalink
add command DP
Browse files Browse the repository at this point in the history
  • Loading branch information
Liu Yuning committed May 21, 2017
1 parent dc23a46 commit d4deb16
Show file tree
Hide file tree
Showing 4 changed files with 127 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/designpattern/command/Command.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package designpattern.command;

import java.util.List;

/**
* 用来声明执行操作的接口
*
* @author liu yuning
*
*/
public abstract class Command {

protected List<Reciever> recievers;

public Command(List<Reciever> recievers) {
this.recievers = recievers;
}

public void addRecievers(Reciever reciever) {
this.recievers.add(reciever);
}

public abstract void execute();

}

// 将一个接收者对象绑定于一个动作,调用接收者相应的操作,以实现execute
class ConcreteCommand extends Command {

public ConcreteCommand(List<Reciever> recievers) {
super(recievers);
}

@Override
public void execute() {
for (Reciever reciever : recievers) {
reciever.action();
}
}

}
29 changes: 29 additions & 0 deletions src/designpattern/command/CommandClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package designpattern.command;

import java.util.ArrayList;
import java.util.List;

/**
* 创建一个具体命令对象并设定它的接收者
*
* @author liu yuning
*
*/
public class CommandClient {

public static void main(String[] args) {
List<Reciever> recievers = new ArrayList<Reciever>();

recievers.add(new RecieverA());
recievers.add(new RecieverB());
recievers.add(new RecieverC());

Command command = new ConcreteCommand(recievers);
Invoker invoker = new Invoker();

invoker.setCommand(command);
invoker.executeCommand();

}

}
21 changes: 21 additions & 0 deletions src/designpattern/command/Invoker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package designpattern.command;

/**
* 要求该命令执行这个请求
*
* @author liu yuning
*
*/
public class Invoker {

private Command command;

public void setCommand(Command command) {
this.command = command;
}

public void executeCommand() {
command.execute();
}

}
36 changes: 36 additions & 0 deletions src/designpattern/command/Reciever.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package designpattern.command;

/**
* 知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接收者。真正执行请求的地方!
*
* @author liu yuning
*
*/
interface Reciever {
public void action();
}

class RecieverA implements Reciever {

@Override
public void action() {
System.out.println("RecieverA执行请求!");
}

}

class RecieverB implements Reciever {

@Override
public void action() {
System.out.println("RecieverB执行请求!");
}
}

class RecieverC implements Reciever {

@Override
public void action() {
System.out.println("RecieverC执行请求!");
}
}

0 comments on commit d4deb16

Please sign in to comment.