1.简介
The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
(命令模式是一种行为设计模式,其中一个对象用于封装所有信息,以便在以后执行某个操作或触发某个事件。此信息包括方法名称、拥有方法的对象和方法参数的值)
—— quote from Wikipedia
1 |
|
2.命令模式的优缺点:
优点:
1、降低了系统耦合度。
2、新的命令可以很容易添加到系统中去。
缺点:
使用命令模式可能会导致某些系统有过多的具体命令类。
3.相关实例解析
1举个常见的例子,小明去上海旅游,有出发和返程的方法。然后代理类放入相关的类,将其正确的执行。
相关代码:
1 |
|
输出结果:
1 |
|