命令模式: 接收者(执行者)内实现具体的事件; 命令类持有接收者的引用,并提供方法调用接收者的方法;请求者持有一个或多个命令,并提供调用命令的方法;
接收者(执行者)
<pre>
public class Receiver {
private static final String TAG = "Receiver";
public void action() {
Log.i(TAG, "action: ");
}
}
</pre>
命令类
<pre>
public interface Command {
void execute();
}
public class CommandImpl implements Command {
private Receiver receiver;
public CommandImpl(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.action();
}
}
</pre>
请求者
<pre>
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void action() {
command.execute();
}
}
</pre>
使用
<pre>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Receiver receiver = new Receiver();
Command command = new CommandImpl(receiver);
Invoker invoker = new Invoker(command);
invoker.action();
}
}
</pre>
log
<pre>
03-10 19:14:48.843 15277-15277/com.lerz.commanddemo I/Receiver: action:
</pre>
网友评论