设计模式总结通过命令模式.docx

上传人:b****8 文档编号:9650691 上传时间:2023-02-05 格式:DOCX 页数:27 大小:145.46KB
下载 相关 举报
设计模式总结通过命令模式.docx_第1页
第1页 / 共27页
设计模式总结通过命令模式.docx_第2页
第2页 / 共27页
设计模式总结通过命令模式.docx_第3页
第3页 / 共27页
设计模式总结通过命令模式.docx_第4页
第4页 / 共27页
设计模式总结通过命令模式.docx_第5页
第5页 / 共27页
点击查看更多>>
下载资源
资源描述

设计模式总结通过命令模式.docx

《设计模式总结通过命令模式.docx》由会员分享,可在线阅读,更多相关《设计模式总结通过命令模式.docx(27页珍藏版)》请在冰豆网上搜索。

设计模式总结通过命令模式.docx

设计模式总结通过命令模式

注:

文档内容基本上来自于网上,并加上自己的理解而成。

有的觉得网友总结得非常好,就完全照搬下来,供学习之用。

然而,有的摘抄并没有加上原链接和出处,请谅解。

通过命令模式,通过在客户端和具体的命令之间添加一层Invoker,剪断了客户端和具体服务提供者之间的耦合,降低了两者之间的耦合度,同时也增加了灵活性,比如我们可以灵活的某一个请求的服务提供者,通过单独的服务提供者Command类,可以很方便的提供redo和undo的功能等等,这些都是命令模式的优势。

在软件系统中,“行为请求者”与“行为实现者”通常呈现一种“紧耦合”。

但在某些场合,比如要对行为进行“记录、撤销/重做、事务”等处理,这种无法抵御变化的紧耦合是不合适的。

在这种情况下,如何将“行为请求者”与“行为实现者”解耦?

将一组行为抽象为对象,实现二者之间的松耦合。

这就是命令模式(CommandPattern)

即命令模式的核心是要解决“行为请求者”和“行为实现”都之间的耦合,以达到灵活多变的效果。

目标:

客户只需要发命令,而不需要管命令是如何被执行的!

Commandpattern

FromWikipedia,thefreeencyclopedia

Thisarticleincludesa listofreferences,relatedreadingor externallinks,but itssourcesremainunclearbecauseitlacks inlinecitations. Please improve thisarticlebyintroducingmoreprecisecitations. (December2012)

In object-orientedprogramming,the commandpattern isa behavioural designpattern inwhich anobjectisusedtorepresentand encapsulate alltheinformationneededtocallamethodatalatertime.Thisinformationincludesthemethodname,theobjectthatownsthemethodandvaluesforthemethodparameters.

Fourtermsalwaysassociatedwiththecommandpatternare command, receiver, invoker and client. 

Aconcrete command objecthasa receiver objectandinvokesamethodofthereceiverinawaythatisspecifictothatreceiver'sclass(即在concretecommandObject里面有receiver的成员变量,并且有触发receiver动作的方法,这个方法是所有receiver所共有的接口级别的方法).Thereceiverthendoesthework. 

Aconcretecommandobjectisseparatelypassedtoan invoker object,whichinvokesthecommand,andoptionallydoesbookkeepingaboutthecommandexecution.Anyconcretecommandobjectcanbepassedtothesameinvokerobject(即在Invoker有一个接受ConcreteCommand的方法,形如setCommand(XXX)).Bothaninvokerobjectandseveralconcretecommandobjectsareheldbya client object(Client创建具体的ConcreteCommand).Theclientcontainsthedecisionmakingaboutwhichcommandstoexecuteatwhichpoints. Toexecuteacommand,itpassesthecommandobjecttotheinvokerobject. Seeexamplecodebelow.

Usingcommandobjectsmakesiteasiertoconstructgeneralcomponentsthatneedtodelegate,sequenceorexecutemethodcallsatatimeoftheirchoosingwithouttheneedtoknowtheclassofthemethodorthemethodparameters.Usinganinvokerobjectallowsbookkeepingaboutcommandexecutionstobeconvenientlyperformed,aswellasimplementingdifferentmodesforcommands,whicharemanagedbytheinvokerobject,withouttheneedfortheclienttobeawareoftheexistenceofbookkeepingormodes.

Contents

  [hide] 

∙1 Uses

∙2 Structure

∙3 Terminology

∙4 Example

∙4.1 C#

∙4.2 Java

∙4.3 Python

∙4.4 Scala

∙4.5 Javascript

∙5 Seealso

∙6 References

∙7 Externallinks

[edit]Uses

Commandobjectsareusefulforimplementing:

GUIbuttonsandmenuitems 

In Swing and BorlandDelphi programming,an Action isacommandobject.Inadditiontotheabilitytoperformthedesiredcommand,an Action mayhaveanassociatedicon,keyboardshortcut,tooltiptext,andsoon.AtoolbarbuttonormenuitemcomponentmaybecompletelyinitializedusingonlytheAction object.

Macro recording 

Ifalluseractionsarerepresentedbycommandobjects,aprogramcanrecordasequenceofactionssimplybykeepingalistofthecommandobjectsastheyareexecuted.Itcanthen"playback"thesameactionsbyexecutingthesamecommandobjectsagaininsequence.Iftheprogramembedsascriptingengine,eachcommandobjectcanimplementa toScript() method,anduseractionscanthenbeeasilyrecordedasscripts.

MobileCode 

UsinglanguagessuchasJavawherecodecanbestreamed/slurpedfromonelocationtoanotherviaURLClassloadersandCodebasesthecommandscanenablenewbehaviortobedeliveredtoremotelocations(EJBCommand,MasterWorker)

Multi-level undo 

Ifalluseractionsinaprogramareimplementedascommandobjects,theprogramcankeepastackofthemostrecentlyexecutedcommands.Whentheuserwantstoundoacommand,theprogramsimplypopsthemostrecentcommandobjectandexecutesits undo() method.

Networking 

Itispossibletosendwholecommandobjectsacrossthenetworktobeexecutedontheothermachines,forexampleplayeractionsincomputergames.

ParallelProcessing 

Wherethecommandsarewrittenastaskstoasharedresourceandexecutedbymanythreadsinparallel(possiblyonremotemachines-thisvariantisoftenreferredtoastheMaster/Workerpattern)

Progressbars 

Supposeaprogramhasasequenceofcommandsthatitexecutesinorder.Ifeachcommandobjecthasa getEstimatedDuration() method,theprogramcaneasilyestimatethetotalduration.Itcanshowaprogressbarthatmeaningfullyreflectshowclosetheprogramistocompletingallthetasks.

Threadpools 

Atypical,general-purposethreadpoolclassmighthaveapublic addTask() methodthataddsaworkitemtoaninternalqueueoftaskswaitingtobedone.Itmaintainsapoolofthreadsthatexecutecommandsfromthequeue.Theitemsinthequeuearecommandobjects.Typicallytheseobjectsimplementacommoninterfacesuchas java.lang.Runnable thatallowsthethreadpooltoexecutethecommandeventhoughthethreadpoolclassitselfwaswrittenwithoutanyknowledgeofthespecifictasksforwhichitwouldbeused.

Transactional behavior 

Similartoundo,adatabaseengineorsoftwareinstallermaykeepalistofoperationsthathavebeenorwillbeperformed.Shouldoneofthemfail,allotherscanbereversedordiscarded(usuallycalled rollback).Forexample,iftwodatabasetablesthatrefertoeachothermustbeupdated,andthesecondupdatefails,thetransactioncanberolledback,sothatthefirsttabledoesnotnowcontainaninvalidreference.

Wizards 

Oftenawizardpresentsseveralpagesofconfigurationforasingleactionthathappensonlywhentheuserclicksthe"Finish"buttononthelastpage.Inthesecases,anaturalwaytoseparateuserinterfacecodefromapplicationcodeistoimplementthewizardusingacommandobject.Thecommandobjectiscreatedwhenthewizardisfirstdisplayed.EachwizardpagestoresitsGUIchangesinthecommandobject,sotheobjectispopulatedastheuserprogresses."Finish"simplytriggersacallto execute().Thisway,thecommandclasscontainsnouserinterfacecode.

[edit]Structure

∙UPDATE:

TheexplanationfortheReceiverblockaboveshouldbe"Theactualworktobedonebythecommand(action)"

[edit]Terminology

Theterminologyusedtodescribecommandpatternimplementationsisnotconsistentandcanthereforebeconfusing.Thisistheresultof ambiguity,theuseof synonyms,andimplementationsthatmayobscuretheoriginalpatternbygoingwellbeyondit.

1.Ambiguity.

2.Theterm command isambiguous.Forexample, moveup,moveup mayrefertoasingle(moveup)commandthatshouldbeexecutedtwice,oritmayrefertotwocommands,eachofwhichhappenstodothesamething(moveup).Iftheformercommandisaddedtwicetoanundostack,bothitemsonthestackrefertothesamecommandinstance.Thismaybeappropriatewhenacommandcanalwaysbeundonethesameway(e.g.movedown).Boththe GangofFour andthe Javaexamplebelow usethisinterpretationoftheterm command.Ontheotherhand,ifthelattercommandsareaddedtoanundostack,thestackreferstotwoseparateobjects.Thismaybeappropriatewheneachobjectonthestackmustcontaininformationthatallowsthecommandtobeundone.Forexample,toundoa deleteselection command,theobjectmaycontainacopyofthedeletedtextsothatitcanbere-inserted,ifthe deleteselection commandmustbeundone.Notethatusingaseparateobjectforeachinvocationofacommandisalsoanexampleofthe chainofresponsibilitypattern.

3.Theterm execute isalsoambiguous.Itmayrefertorunningthecodeidentifiedbythecommandobject's execute method.However,inMicrosoft's WindowsPresentationFoundation acommandisconsideredtohavebeenexecutedwhenthecommand's execute methodhasbeeninvoked,butthatdoesnotnecessarilymeanthattheapplicationcodehasrun.Thatoccursonlyaftersomefurthereventprocessing.

4.Synonymsand homonyms.

5.Client,Source,Invoker:

thebutton,toolbarbutton,ormenuitemclicked,theshortcutkeypressedbytheuser.

6.CommandObject,RoutedCommandObject,ActionObject:

asingletonobject(e.g.thereisonlyoneCopyCommandobject),whichknowsaboutshortcutkeys,buttonimages,commandtext,etc.relatedtothecommand.Asource/invokerobjectcallstheCommand/Actionobject'sexecute/performActionmethod.TheCommand/Actionobjectnotifiestheappropriatesource/invokerobjectswhentheavailabilityofacommand/actionhaschanged.Thisallowsbuttonsandmenuitemstobecomeinactive(grayedout)whenacommand/actioncannotbeexecuted/performed.

7.Receiver,TargetObject:

theobjectthatisabouttobecopied,pasted,moved,etc.Thereceiverobjectownsthemethodthatiscalledbythecommand's execute method.Thereceiveristypicallyalsothetargetobject.Forexample,ifthereceiverobjectisa cursor andthemethodiscalled moveUp,thenonewouldexpectthatthecursoristhetargetofthemoveUpaction.Ontheotherhand,ifthecodeisdefinedbythecommandobjectitself,thetargetobjectwillbeadifferentobjectentirely.

8.CommandObject,routedeventargs,eventobject:

theobjectthatispassedfromthesourcetotheCommand/Actionobject,totheTargetobjecttothecodethatdoesthework.Eachbuttonclickorshortcutkeyresultsinanewcommand/eventobject.Someimplementationsaddmoreinformationtothecommand/eventobjectasitisbeingpassedfromoneobject(e.g.CopyCommand)toanother(e.g.documentsection).Otherimplementationsputcommand/eventobjectsinothereventobjects(likeaboxinsideabiggerbox)astheymovealongthe

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 总结汇报 > 学习总结

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1