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

源自: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();
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值