命令模式
有如下的角色:
(1)调用者(invoker)
(2)命令接收者(receiver)
(3)客户端(client)
(4)命令对象(command)
public interface Command {
public void execute();
}
public class ConcreteCommand implements Command { private Receiver receiver = null;
private String state; public ConcreteCommand(Receiver receiver){
this.receiver = receiver;
}
public void execute() {
receiver.action();
}
} public class Receiver {
public void action(){
//真正执行命令操作的功能代码
}
} public class Invoker {
private Command command = null; public void setCommand(Command command) {
this.command = command;
} public void runCommand() {
command.execute();
}
} public class Client {
public void assemble(){
//创建接收者
Receiver receiver = new Receiver();
//创建命令对象,设定它的接收者
Command command = new ConcreteCommand(receiver);
//创建Invoker,把命令对象设置进去
Invoker invoker = new Invoker();
invoker.setCommand(command);
}
}
在Netd的命令模式中Client角色和invoker角色都为CommandListener
receiver为CommandListener中各种各种Controller,其中有
FirewallController *CommandListener::sFirewallCtrl = NULL;
与上面的命令模式不同,各种Command为CommandListener的内部类,可直接使用receiver,而不用将receiver传递给Command对象。还有一点不同的就是,这里的各种controller作为receiver没有像例子中有统一的action函数,而是直接在runCommand函数(例子中是Command类的execute函数)使用controller实现各种动作的执行。
Netd的各种命令分发路径如下:
SocketListener::runListener
->FameworkListener::onDataAvailable
-> FameworkListener::dispatchCommand
-> CommandListener::各种Cmd::runCommand
(版权所有,转载请告知)