小A:“命令模式怎样去实现它?”
大B:“命令模式里边一般都有以下几个角色:客户端,请求者,命令接口,命令实现,接受者。下边是简单命令模式的实现代码实现。”
publicclassClient{
publicstaticvoidmain(String[]args){
Receiverreceiver=newReceiver();
CommandmandOne=newConcreteCommandOne(receiver);
CommandmandTwo=newConcreteCommandTwo(receiver);
Invokerinvoker=newInvoker(mandOne,mandTwo);
invoker.actionOne();
invoker.actionTwo();
}
}
publicclassInvoker
{
privateCommandmandOne;
privateCommandmandTwo;
publicInvoker(CommandmandOne,CommandmandTwo){
this.orgmandOne=mandOne;
this.orgmandTwo=mandTwo;
}
publicvoidactionOne(){
mandOne.execute();
}
publicvoidactionTwo(){
mandTwo.execute();
}
}
publicinterfaceCommand{
voidexecute();
}
publicclassConcreteCommandOneimplementsCommand{
privateReceiverreceiver
publicConcreteCommandOne(Receiverreceiver){
this.receiver=receiver;
}
publicvoidexecute(){
receiver.actionOne();
}
}
publicclassConcreteCommandTwoimplementsCommand{
privateReceiverreceiver
publicConcreteCommandTwo(Receiverreceiver){
this.receiver=receiver;
}
publicvoidexecute(){
receiver.actionTwo();
}
}
publicclassReceiver{
publicReceiver(){
//
}
publicvoidactionOne(){
System.out.println(“ActionOnehasbeentaken.”);
}
publicvoidactionTwo(){
System.out.println(“ActionTwohasbeentaken.”);
}
}