命令模式: 接收者(執(zhí)行者)內(nèi)實現(xiàn)具體的事件; 命令類持有接收者的引用前标,并提供方法調(diào)用接收者的方法化戳;請求者持有一個或多個命令睬澡,并提供調(diào)用命令的方法艇拍;
接收者(執(zhí)行者)
<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>