菜鸟硕枫设计模式系列之15 命令模式

命令模式是一种行为模式,解耦了发送方与接收方。它将请求封装成一个对象,使得可以用不同的请求使得客户端参数化,典型应用在支持redo undo 事物等场景。

命令模式类图:
[img]http://dl.iteye.com/upload/attachment/364675/25714191-2d46-3425-8a2b-af7755b81aa0.jpg[/img]


具体代码示例:
命令接口:

package commandPattern;

public abstract class Command {
public Reciever reciever;

public abstract void excute();

public void setReciever(Reciever reciever) {
this.reciever = reciever;
}

}


具体命令:


package commandPattern;

public class ConcreteCommandA extends Command{

@Override
public void excute() {
System.out.println("hello,this is "+this.getClass()+" working");
reciever.concreteAction4A();
}

}



package commandPattern;

public class ConcreteCommandB extends Command{

@Override
public void excute() {
System.out.println("hello,this is "+this.getClass()+" working");
reciever.concreteAction4B();
}

}

Invoker (命令调用者)

package commandPattern;

public class Invoker {

private Command command;

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

}

Reciever (命令执行者)

package commandPattern;

public class Reciever {

void concreteAction4A(){
System.out.println("A is working");
}

void concreteAction4B(){
System.out.println("B is working");
}
}


测试类:

package commandPattern;

public class testCommandPattern {

public static void main(String[]args){
Reciever reciever = new Reciever();

Invoker a = new Invoker();
Command commandA = new ConcreteCommandA();
commandA.setReciever(reciever);
a.setCommand(commandA);

Invoker b = new Invoker();
Command commandB = new ConcreteCommandB();
commandB.setReciever(reciever);
b.setCommand(commandB);

a.excute();
b.excute();
}
}


说明:
这其中隐含了代理模式。其中invoker就是一个代理,对命令实现而言,它无需关心谁调用;而对调用者而言,没有必要关心调用哪个reciever方法;当然也可以用不同的reciever去实现不同的功能方法。在此只是说明执行过程和方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值