您的位置:首页 > 编程语言 > Java开发

23种设计模式 第三部分 关系模式(6)命令模式

2016-10-04 00:02 549 查看




理解

命令模式即按照客户端传入的要求完成特定的功能。将来自客户端的请求传入一个对象,从而使你可用不同的请求对客户进行参数化。用于“行为请求者”与“行为实现者”解耦,可实现二者之间的松耦合,以便适应变化。分离变化与不变的因素。

一个对象调用另一个对象,一般情况下的调用过程是:创建目标对象实例;设置调用参数;调用目标对象的方法。需要使用一个专门的类对这种调用过程加以封装时,我们把这种专门的类称作command类。

用途



整个调用过程比较繁杂,或者存在多处这种调用。这时,使用Command类对该调用加以封装,便于功能的再利用。
调用前后需要对调用参数进行某些处理。

调用前后需要进行某些额外处理,比如日志,缓存,记录历史操作等

举个例子,司令员下令让士兵去干件事情,从整个事情的角度来考虑,司令员的作用是,发出口令,口令经过传递,传到了士兵耳朵里,士兵去执行。这个过程好在,三者相互解耦,任何一方都不用去依赖其他人,只需要做好自己的事儿就行,司令员要的是结果,不会去关注到底士兵是怎么实现的。我们看看关系图:



命令模式的参与角色:

(1)抽象命令角色(Command):抽象命令,包含命令执行的抽象方法

(2)命令接收者(Receiver):命令接收者角色,它包含所有命令的具体行为实现方法。

(3)具体命令角色(ConcreteCommand):它包含一个命令接收者对象,并调用接收者的对象相应实现方法。

(4)命令调用者角色(Invoker):提供给客户端调用,接收客户端所传递的具体命令对象。

Invoker是调用者(司令员),Receiver是被调用者(士兵),MyCommand是命令,实现了Command接口,持有接收对象

代码:

public interface Command {
public void exe();
}
public class MyCommand implements Command {

private Receiver receiver;

public MyCommand(Receiver receiver) {
this.receiver = receiver;
}

@Override
public void exe() {
receiver.action();
}
}
public class Receiver {
public void action(){
System.out.println("command received!");
}
}
public class Invoker {

private Command command;

public Invoker(Command command) {
this.command = command;
}

public void action(){
command.exe();
}
}
public class Test {

public static void main(String[] args) {
Receiver receiver = new Receiver();
Command cmd = new MyCommand(receiver);
Invoker invoker = new Invoker(cmd);
invoker.action();
}
}
输出:command received!
命令模式的目的就是达到命令的发出者和执行者之间解耦,实现请求和执行分开,熟悉Struts的同学应该知道,Struts其实就是一种将请求和呈现分离的技术,其中必然涉及命令模式的思想!

其他资料


Intent

Encapsulate a request as an object, thereby letting you parametrize clients with different requests, queue or log requests, and support undoable operations.
Promote "invocation of a method on an object" to full object status
An object-oriented callback


Problem

Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request.


Discussion

Command decouples the object that invokes the operation from the one that knows how to perform it. To achieve this separation, the designer creates an abstract base class that maps a receiver (an object) with an action (a pointer to a member function). The
base class contains an
execute()
method that simply calls the action on the receiver.

All clients of Command objects treat each object as a "black box" by simply invoking the object's virtual
execute()
method
whenever the client requires the object's "service".

A Command class holds some subset of the following: an object, a method to be applied to the object, and the arguments to be passed when the method is applied. The Command's "execute" method then causes the pieces to come together.

Sequences of Command objects can be assembled into composite (or macro) commands.


Structure

The client that creates a command is not the same client that executes it. This separation provides flexibility in the timing and sequencing of commands. Materializing commands as objects means they can be passed, staged, shared, loaded in a table, and otherwise
instrumented or manipulated like any other object.



Command objects can be thought of as "tokens" that are created by one client that knows what need to be done, and passed to another client that has the resources for doing it.

Example:

The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order or command from a customer
and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of "checks" used by each waiter is not dependent on the menu, and therefore they can support commands to cook many different items.



其他实现

import java.util.*;
public class CommandQueue {

interface Command { void execute(); }

static class DomesticEngineer implements Command {
public void execute() {
System.out.println( "take out the trash" );
}  }

static class Politician implements Command {
public void execute() {
System.out.println( "take money from the rich, take votes from the poor" );
}  }

static class Programmer implements Command {
public void execute() {
System.out.println( "sell the bugs, charge extra for the fixes" );
}  }

public static List produceRequests() {
List queue = new ArrayList();
queue.add( new DomesticEngineer() );
queue.add( new Politician() );
queue.add( new Programmer() );
return queue;
}

public static void workOffRequests( List queue ) {
for (Iterator it = queue.iterator(); it.hasNext(); )
((Command)it.next()).execute();
}

public static void main( String[] args ) {
List queue = produceRequests();
workOffRequests( queue );
}}
输出

take out the trash
take money from the rich, take votes from the poor
sell the bugs, charge extra for the fixes
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息