第188章
小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.”);
}
}