设计模式总结 通过命令模式
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
注:
文档内容基本上来自于网上,并加上自己的理解而成。有的觉得网友总结得非常好,就完全照搬下来,供学习之用。然而,有的摘抄并没有加上原链接和出处,请谅解。
通过命令模式,通过在客户端和具体的命令之间添加一层Invoker,剪断了客户端和具体服务提供者之间的耦合,降低了两者之间的耦合度,同时也增加了灵活性,比如我们可以灵活的某一个请求的服务提供者,通过单独的服务提供者Command类,可以很方便的提供redo和undo的功能等等,这些都是命令模式的优势。
在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。在这种情况下,如何将“行为请求者”与“行为实现者”解耦?将一组行为抽象为对象,实现二者之间的松耦合。这就是命令模式(Command Pattern)
即命令模式的核心是要解决“行为请求者”和“行为实现”都之间的耦合,以达到灵活多变的效果。
目标:
客户只需要发命令,而不需要管命令是如何被执行的!Command pattern
From Wikipedia,the free encyclopedia
In object-oriented programming,the command pattern is
the method and values for the method parameters.
∙
∙
∙
∙
∙
∙
∙
∙
∙
∙
∙
[edit]Uses
[edit]Structure
UPDATE:The explanation for the Receiver block above should be
"The actual work to be done by the command(action)"
[edit]Terminology
1.Ambiguity.
2.The term command is
ambiguous.For
example,move up,move
up may refer to a single
5.Client,Source,Invoker:the
button,toolbar button,or
menu item clicked,the
shortcut key pressed by the
user.
mand Object,Routed
Command Object,Action
Object:a singleton object
(e.g.there is only one
CopyCommand object),
which knows about shortcut
keys,button images,
command text,etc.related
to the command.A
source/invoker object calls
the Command/Action
object's
execute/performAction
method.The
Command/Action object
notifies the appropriate
source/invoker objects
when the availability of a
command/action has
changed.This allows
buttons and menu items to
become inactive(grayed out) when a command/action
cannot be
executed/performed.
7.Receiver,Target Object:
the object that is about to
be copied,pasted,moved,
etc.The receiver object
owns the method that is
called by the
command's execute method.
The receiver is typically also
the target object.For
example,if the receiver object is a cursor and the method is called moveUp,
then one would expect that
the cursor is the target of
the moveUp action.On the
other hand,if the code is
defined by the command
object itself,the target
object will be a different
object entirely.
mand Object,routed
event args,event object:
the object that is passed
from the source to the
Command/Action object,to
the Target object to the
code that does the work.
Each button click or
shortcut key results in a new
command/event object.