Java设计模式-----Command模式 .

来源:互联网 发布:网络改写的小说 编辑:程序博客网 时间:2024/06/14 15:35
 

源自:http://www.blogjava.net/flustar/archive/2007/12/05/command.html

Command模式:

一、 Command模式定义:
将一个请求封装为一个对象,从而使你不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
二、 模式解说
Commad模式是一种对象行为模式,它可以对发送者(sender)和接收者(receiver)完全解耦(decoupling)。("发送者" 是请求操作的对象,"接收者" 是接收请求并执行某操作的对象。有了 "解耦",发送者对接收者的接口一无所知。)这里,"请求"(request)这个术语指的是要被执行的命令。Command模式还让我们可以对 "何时" 以及 "如何" 完成请求进行改变。因此,Command模式为我们提供了灵活性和可扩展性。
三、怎么使用?
1) 定义一个Command接口,接口中有一个统一的方法,这就是将请求/命令封装为对象。
2) 定义具体不同命令类ConcreteCommand实现Command接口。
3) 定义一个命令的调用角色Invoker。
4) 定义一个命令执行状态的接收者Receiver(非必须)。

例子:

public class Document {public void display() {System.out.println("显示文档内容");}public void undo() {System.out.println("撤销文档内容");}public void redo() {System.out.println("重做文档内容");}}public interface DocumentCommand {public void execute();}public class DisplayCommand implements DocumentCommand {private Document document;public DisplayCommand(Document doc) {document = doc;}public void execute() {document.display();}}public class RedoCommand implements DocumentCommand {private Document document;public RedoCommand(Document doc) {document = doc;}public void execute() {document.redo();}}public class UndoCommand implements DocumentCommand {private Document document;public UndoCommand(Document doc) {document = doc;}public void execute() {document.undo();}}public class DocumentInvoker {private DisplayCommand _dcmd;private UndoCommand _ucmd;private RedoCommand _rcmd;public DocumentInvoker(DisplayCommand dcmd, UndoCommand ucmd,RedoCommand rcmd) {this._dcmd = dcmd;this._ucmd = ucmd;this._rcmd = rcmd;}public void display() {_dcmd.execute();}public void undo() {_ucmd.execute();}public void redo() {_rcmd.execute();}}public class CommandTest {public static void main(String[] args) {Document doc = new Document();DisplayCommand display = new DisplayCommand(doc);UndoCommand undo = new UndoCommand(doc);RedoCommand redo = new RedoCommand(doc);DocumentInvoker invoker = new DocumentInvoker(display, undo, redo);invoker.display();invoker.undo();invoker.redo();}}



转自:http://blog.csdn.net/kunshan_shenbin/article/details/2516501

原创粉丝点击