命令模式
Posted diameter
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了命令模式相关的知识,希望对你有一定的参考价值。
名称:
命令模式(Command Pattern)
问题:
The Command pattern encapsulates a request in an object, which enables you to store the command, pass the command to a method, and return the command like any other object.
解决方案:
1、 模式的参与者
1、Command
-声明执行操作的接口。
2、ConcreteCommand
-将一个接受者对象绑定于一个动作。
-调用接受者相应的操作,以实现Execute。
3、Client
-创建一个具体命令对象并设定它的接受者。
4、Invoker
-要求该命令执行这个请求。
5、Receiver
-知道如何实施与执行一个请求相关的操作。任何类都可能作为一个接受。
2.实现方式
interface Command { public void execute(); }
class ConcreteCommand implements Command { private Receiver receiver; ConcreteCommand() { receiver=new Receiver(); } public void execute() { receiver.action(); } }
class Receiver { public void action() { System.out.println("action..."); } }
class Invoker { private Command command; public Invoker(Command command) { this.command=command; } public void setCommand(Command command) { this.command=command; } public void call() { command.execute(); } }
参考资料
《设计模式:可复用面向对象软件的基础》
以上是关于命令模式的主要内容,如果未能解决你的问题,请参考以下文章