优点:
解耦了发送者和接受者之间联系。 发送者调用一个操作,接受者接受请求执行相应的动作,因为使用Command模式解耦,发送者无需知道接受者任何接口。
不少Command模式的代码都是针对图形界面的,它实际就是菜单命令,我们在一个下拉菜单选择一个命令时,然后会执行一些动作.
将这些命令封装成在一个类中,然后用户(调用者)再对这个类进行操作,这就是Command模式,换句话说,本来用户(调用者)是直接 调用这些命令的,如菜单上打开文档(调用者),就直接指向打开文档的代码,使用Command模式,就是在这两者之间增加一个中间者,将这种直接关系拗 断,同时两者之间都隔离,基本没有关系了.
显然这样做的好处是符合封装的特性,降低耦合度,Command是将对行为进行封装的典型模式,Factory是将创建进行封装的模式,
从Command模式,我也发现设计模式一个"通病":好象喜欢将简单的问题复杂化, 喜欢在不同类中增加第三者,当然这样做有利于代码的健壮性
可维护性 还有复用性.
The idea and implementation
of the Command design pattern is quite simple, as we will see in the
diagram below, needing only few extra classes implemented.
The classes participating in the pattern are:
- Command - declares an interface for executing an operation;
-
ConcreteCommand - extends the Command interface, implementing the
Execute method by invoking the corresponding operations on Receiver. It
defines a link between the Receiver and the action.
- Client - creates a ConcreteCommand object and sets its receiver;
- Invoker - asks the command to carry out the request;
- Receiver - knows how to perform the operations;
Here is a sample code of a classic implementation of this pattern for placing orders for buying and selling stocks:

| public interface Order { public abstract void execute ( ); } // Receiver class. class StockTrade { public void buy() { System.out.println("You want to buy stocks"); } public void sell() { System.out.println("You want to sell stocks "); } } // Invoker. class Agent { private m_ordersQueue = new ArrayList(); public Agent() { } void placeOrder(Order order) { ordersQueue.addLast(order); order.execute(ordersQueue.getFirstAndRemove()); } } //ConcreteCommand Class. class BuyStockOrder implements Order { private StockTrade stock; public BuyStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . buy( ); } } //ConcreteCommand Class. class SellStockOrder implements Order { private StockTrade stock; public SellStockOrder ( StockTrade st) { stock = st; } public void execute( ) { stock . sell( ); } } // Client public class Client { public static void main(String[] args) { StockTrade stock = new StockTrade(); BuyStockOrder bsc = new BuyStockOrder (stock); SellStockOrder ssc = new SellStockOrder (stock); Agent agent = new Agent(); agent.placeOrder(bsc); // Buy Shares agent.placeOrder(ssc); // Sell Shares } } |
应用场景:
-
参数化
对象
取决于
他们
必须执行
的
行动
- 指定
或添加
在队列中,
在不同的时间
时刻
执行
的
请求
-
支持
撤消
行动
(
记录
Execute方法
可
的
状态
,并允许
返回该状态
)
-
构造高级
业务
系统
-
分离调用
对象和执行
对象
。
由于
这种用法
,
它
也被称为
生产者 - 消费者
设计模式
。
The example of the meal order at a restaurant is a very good one when trying to explain better how the pattern works:
The
waiter (Invoker) takes the order from the customer on his pad. The
order is then queued for the order cook and gets to the cook (Receiver)
where it is processed.