优点:
- 类间解耦
- 可扩展性
- 与其它模式组更优秀
缺点:
- N个命令,N个子类,类膨胀
角色分类:
- Receiver 接受者:也就是具体工作者
- Command:需要执行的所有命令在这里申明
- Invoker调用者:接到命令,并执行命令
Receiver
package com.memory.commond;
/**
* 接收者
*
* @可以有多个接收者
*
* @author Administrator
*
*/
public abstract class Receiver {
/**
* 执行任务
*/
public abstract void doTask();
}
package com.memory.commond;
/**
* 具体接收者1,
*
* @author Administrator
*
*/
public class ConcreteReceiver1 extends Receiver {
@Override
public void doTask() {
// TODO Auto-generated method stub
System.out.println("接收者1,执行任务");
}
}
Commond类
package com.memory.commond;
/**
* 命令
*
* @author Administrator
*
*/
public abstract class Commond {
// /**
// * 接收者
// */
// protected final Receiver mReceiver;
//
// public Commond(Receiver receiver) {
// this.mReceiver = receiver;
// }
/**
* 执行命令
*/
public abstract void execute();
}
package com.memory.commond;
/**
* 具体commond
*
* @author Administrator
*
*/
public class ConcreteCommond1 extends Commond {
public ConcreteCommond1() {
// TODO Auto-generated constructor stub
//屏蔽低层
this.mReceiver = new ConcreteReceiver1();
}
/**
* 接收者
*/
Receiver mReceiver;
public ConcreteCommond1(Receiver receiver) {
// super(receiver);
this.mReceiver = receiver;
}
@Override
public void execute() {
// TODO Auto-generated method stub
System.out.println("命令发布人1");
this.mReceiver.doTask();
}
}
Invoker类
package com.memory.commond;
/**
* 负责人
*
* @author Administrator
*
*/
public class Invoker {
/**
* 命令
*/
private Commond mCommond;
/**
* 设置命令
*
* @param commond
*/
public void setCommond(Commond commond) {
this.mCommond = commond;
}
/**
* 执行命令
*/
public void action() {
this.mCommond.execute();
}
}
测试类
// 命令模式
Invoker invoker = new Invoker();
Receiver receiver = new ConcreteReceiver1();
Commond commond = new ConcreteCommond1(receiver);
invoker.setCommond(commond);
invoker.action();
//输出
启动应用成功!开启美好的一天
命令发布人1
接收者1,执行任务