书城计算机网络大话设计模式
8183300000188

第188章 9 命令模式的实现

小A:“命令模式怎样去实现它?”

大B:“命令模式里边一般都有以下几个角色:客户端,请求者,命令接口,命令实现,接受者。下边是简单命令模式的实现代码实现。”

public class Client{

public static void main(String[]args){

Receiver receiver=new Receiver();

Command commandOne=new ConcreteCommandOne(receiver);

Command commandTwo=new ConcreteCommandTwo(receiver);

Invoker invoker=new Invoker(commandOne,commandTwo);

invoker。actionOne();

invoker。actionTwo();

}

}

public class Invoker

{

private Command commandOne;

private Command commandTwo;

public Invoker(Command commandOne,Command commandTwo){

this。commandOne=commandOne;

this。commandTwo=commandTwo;

}

public void actionOne(){

commandOne。execute();

}

public void actionTwo(){

commandTwo。execute();

}

}

public interface Command{

void execute();

}

public class ConcreteCommandOne implements Command{

private Receiver receiver

public ConcreteCommandOne(Receiver receiver){

this。receiver=receiver;

}

public void execute(){

receiver。actionOne();

}

}

public class ConcreteCommandTwo implements Command{

private Receiver receiver

public ConcreteCommandTwo(Receiver receiver){

this。receiver=receiver;

}

public void execute(){

receiver。actionTwo();

}

}

public class Receiver{

public Receiver(){

//

}

public void actionOne(){

System。out。println(“ActionOne has been taken。”);

}

public void actionTwo(){

System。out。println(“ActionTwo has been taken。”);

}

}