




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1第2章實(shí)例研究:Lexi文檔編輯器AWYSIWYGdocumenteditor.Mixtextandgraphicsfreelyinvariousformattingstyles.TheusualPull-downmenusScrollbarsPageiconsforjumpingaroundthedocument.通過本實(shí)例設(shè)計(jì),學(xué)習(xí)設(shè)計(jì)模式的實(shí)際應(yīng)用lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第1頁(yè)。22.1設(shè)計(jì)問題Lexi設(shè)計(jì)的7個(gè)問題1文檔結(jié)構(gòu):對(duì)文檔內(nèi)部表示的選擇幾乎影響Lexi設(shè)計(jì)的每個(gè)方面。2格式化3修飾用戶界面4支持多種視感標(biāo)準(zhǔn)5支持多種窗口系統(tǒng)6用戶操作7拼寫檢查上述每個(gè)問題都有一組相關(guān)聯(lián)的目標(biāo)集合和限制條件集合。lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第2頁(yè)。32.2文檔結(jié)構(gòu)目標(biāo)保持文檔的物理結(jié)構(gòu)。即將文本和圖形安排到行、列和表等。可視化生成和顯示文檔。根據(jù)顯示位置來映射文檔內(nèi)部表示的元素。限制條件應(yīng)該一致地對(duì)待文本和圖形。應(yīng)該一致地對(duì)待簡(jiǎn)單元素和復(fù)合元素。但文本分析依賴于被分析對(duì)象的類型。lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第3頁(yè)。4解決方案:遞歸組合遞歸組合:Buildingmorecomplexelementsoutofsimplerones.行——列(段落)——頁(yè)(P24第2段第2行)第5行第2列的第10個(gè)元素
Thetenthelementinlinefiveofcolumntwo,隱含:EachobjecttypeneedsacorrespondingclassAllmusthavecompatibleinterfaces(inheritance)圖2包含正文和圖形的遞歸組合圖3遞歸組合的對(duì)象結(jié)構(gòu)lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第4頁(yè)。5Glyph (圖元類)BaseclassforcomposablegraphicalobjectsAnAbstractclassforallobjectsthatcanappearinadocument.Bothprimitiveandcomposed.voidinsert(Glyph)
voidremove(Glyph)
Glyphchild(int)
Glyphparent()管理子圖元的接口booleanintersects(Coord,Coord)判斷一個(gè)指定的點(diǎn)是否與圖元相交voiddraw(Window*)VoidBounds(Rect)在窗口上表示自己返回圖元占用的矩形面積操作任務(wù)基本接口:子類:Character,Image,Space,Row,Columnlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第5頁(yè)。6
圖元類層次Notetheinherentrecursioninthishierarchyi.e.,aRowisaGlyph&aRowalsohasGlyphs!lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第6頁(yè)。7GlyphInterfaceandresponsibilitiesGlyphsknowhowtodrawthemselvesGlyphsknowwhatspacetheyoccupyGlyphsknowtheirchildrenandparentspublicabstractclassGlyph{//appearancepublicabstractvoiddraw(Windoww);publicabstractRectgetBounds();//hitdetectionpublicabstractbooleanintersects(Point);//structurepublicabstractvoidinsert(Glyphg,inti);publicabstractvoidremove(Glyphg);publicabstractGlyphchild(inti);publicabstractGlyphparent();}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第7頁(yè)。8
COMPOSITE
模式objectstructural意圖treatindividualobjects&multiple,recursively-composedobjectsuniformly適用objectsmustbecomposedrecursively,andnodistinctionbetweenindividual&composedelements,andobjectsinstructurecanbetreateduniformlyStructurelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第8頁(yè)。9COMPOSITE
模式(cont’d)objectstructural效果uniformity:treatcomponentsthesameregardlessofcomplexityextensibility:newComponentsubclassesworkwhereveroldonesdo實(shí)現(xiàn)doComponentsknowtheirparents?保持從子部件到父部件的引用能簡(jiǎn)化組合結(jié)構(gòu)的遍歷和管理uniforminterfaceforbothleaves&composites?最大化Component接口don’tallocatestorageforchildreninComponentbaseclassresponsibilityfordeletingchildren由Composite負(fù)責(zé)刪除其子節(jié)點(diǎn)lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第9頁(yè)。102.3格式化格式化:將一個(gè)圖元集合分解為若干行目標(biāo):自動(dòng)換行Breakingupadocumentintolines.ManydifferentalgorithmstradeoffqualityforspeedComplexalgorithms限制條件Wanttokeeptheformattingalgorithmwell-encapsulated.independentofthedocumentstructurecanaddformattingalgorithmwithoutmodifyingGlyphscanaddGlyphswithoutmodifyingtheformattingalgorithm.Wanttomakeitdynamicallychangeable.lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第10頁(yè)。11Composition&CompositorCompositorbaseclassabstractslinebreakingalgorithmsubclassesforspecializedalgorithms,
e.g.,SimpleCompositor,TeXCompositor接口格式化內(nèi)容:voidSetComposition(Composition*)格式化:virtualvoidCompose()Compositioncompositeglyphsuppliedacompositor&leafglyphscreatesrow-columnstructureasdirectedbycompositorlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第11頁(yè)。12Composition&Compositor一個(gè)未格式化的Composition對(duì)象只包含組成文檔基本內(nèi)容的可見圖元,它并不包含像行和列這樣決定文檔物理結(jié)構(gòu)的圖元。Composite對(duì)象只在剛被創(chuàng)建并以待格式化的圖元進(jìn)行初始化后的狀態(tài)當(dāng)Composition對(duì)象需要格式化時(shí),調(diào)用它的Compositor的Compose操作。Compositor依次遍歷Composition的各個(gè)圖元,根據(jù)分行算法插入新的行和列圖元。Generatedinaccordancewithcompositorstrategies&donotaffectcontentsofleafglyphslexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第12頁(yè)。13Compositor&CompositionCompositorclasswillencapsulateaformattingalgorithm.Strategylexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第13頁(yè)。14Compositor&Composition分行算法封裝能增加新的Compositor子類而不觸及Glyph類可在運(yùn)行時(shí)刻改變分行算法在Composition接口中增加一個(gè)SetCompositor操作lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第14頁(yè)。15STRATEGY模式
objectbehavioral意圖defineafamilyofalgorithms,encapsulateeachone,&maketheminterchangeabletoletclients&algorithmsvaryindependently適用性whenanobjectshouldbeconfigurablewithoneofmanyalgorithms,andallalgorithmscanbeencapsulated,andoneinterfacecoversallencapsulations結(jié)構(gòu)lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第15頁(yè)。16STRATEGY模式(cont’d)objectbehavioral效果greaterflexibility,reusecanchangealgorithmsdynamicallystrategycreation&communicationoverheadinflexibleStrategyinterfacesemanticincompatibilityofmultiplestrategiesusedtogether實(shí)現(xiàn)exchanginginformationbetweenaStrategy&itscontextstaticstrategyselectionviatemplateslexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第16頁(yè)。172.4修飾用戶界面Wishtoaddvisiblebordersandscroll-barsaroundpages.Inheritanceisonewaytodoit.leadstoclassproliferationBorderedComposition,ScrollableComposition,BorderedScrollableCompositioninflexibleatrun-timeWillhaveclassesBorderScrollerTheywillbeGlyphstheyarevisibleclientsshouldn’tcareifapagehasaborderornotTheywillbecomposed.butinwhatorder?lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第17頁(yè)。182.4修飾用戶界面目標(biāo):addaframearoundtextcompositionaddscrollingcapability限制條件:embellishmentsshouldbereusablewithoutsubclassing,i.e.,sotheycanbeaddeddynamicallyatruntimeshouldgounnoticedbyclientslexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第18頁(yè)。19解決方案:“Transparent”Enclosure(透明圍欄)Monoglyph:起修飾作用的圖元的抽象類baseclassforglyphshavingonechildoperationsonMonoGlyphpassthroughtochildMonoGlyphsubclasses:Frame:addsaborderofspecifiedwidthScroller:scrolls/clipschild,addsscrollbarslexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第19頁(yè)。20MonoGlyphBordercalls{MonoGlyph.draw();drawBorder();}Decoratorlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第20頁(yè)。21TransparentEnclosuresingle-childcompositioncompatibleinterfacesEnclosurewilldelegateoperationstosinglechild,butcanaddstateaugmentbydoingworkbeforeorafterdelegatingtothechild.lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第21頁(yè)。22DECORATOR
模式objectstructural意圖augmentOneobjectwithnewresponsibilities適用性whenextensionbysubclassingisimpracticalforresponsibilitiesthatcanbewithdrawnStructurelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第22頁(yè)。23DECORATOR模式
(cont’d)objectstructural效果responsibilitiescanbeadded/removedatrun-timeavoidssubclassexplosionrecursivenestingallowsmultipleresponsibilities實(shí)現(xiàn)interfaceconformanceusealightweight,abstractbaseclassforDecoratorlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第23頁(yè)。242.5支持多種視感標(biāo)準(zhǔn)Wanttheapplicationtobeportableacrossdiverseuserinterfacelibraries.EveryuserinterfaceelementwillbeaGlyph.Somewilldelegatetoappropriateplatform-specificoperations.lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第24頁(yè)。25MultipleLook&Feels目標(biāo):supportmultiplelook&feelstandardsgeneric,Motif,Swing,PM,Macintosh,Windows,...extensibleforfuturestandards限制條件:don’trecodeexistingwidgetsorclientsswitchlook&feelwithoutrecompilinglexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第25頁(yè)。26解決方案:AbstractObjectCreationInsteadof
Scrollbar*sb=newMotifScrollbar();use
Scrollbar*sb=factory->createScrollbar();wherefactoryisaninstanceofMotifFactorythisbegsthequestionofwhocreatedthefactory!lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第26頁(yè)。27FactoryInterfacedefines“manufacturinginterface”subclassesproducespecificproductssubclassinstancechosenatrun-time//ThisclassisessentiallyaJavainterfaceclassFactory{public:Scrollbar*createScrollbar()=0;Menu*createMenu()=0;...};lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第27頁(yè)。28ObjectFactoriesUsualmethod:ScrollBarsb=newMotifScrollBar();Factorymethod:ScrollBarsb=guiFactory.createScrollBar();lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第28頁(yè)。29ProductObjectsTheoutputofafactoryisaproduct.abstractconcreteAbstractFactorylexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第29頁(yè)。30BuildingtheFactoryIfknownatcompiletime(e.g.,Lexiv1.0–onlyMotifimplemented).GUIFactoryguiFactory=newMotifFactory();
Setatstartup(Lexiv2.0)StringLandF=appProps.getProperty("LandF");GUIFactoryguiFactory;if(LandF.equals("Motif")) guiFactory=newMotifFactory();...Changeablebyamenucommand(Lexiv3.0)re-initialize‘guiFactory’re-buildtheUISingletonlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第30頁(yè)。31ABSTRACTFACTORY
模式objectcreational意圖createfamiliesofrelatedobjectswithoutspecifyingclassnames適用性whenclientscannotanticipategroupsofclassestoinstantiateStructurelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第31頁(yè)。32ABSTRACTFACTORY模式(cont’d)objectcreational效果flexibility:removestypedependenciesfromclientsabstraction:hidesproduct’scompositionhardtoextendfactoryinterfacetocreatenewproducts實(shí)現(xiàn)parameterizationasawayofcontrollinginterfacesizeconfigurationwithPrototypes,i.e.,determineswhocreatesthefactorieslexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第32頁(yè)。332.6支持多種窗口系統(tǒng)目標(biāo):makecompositionappearinawindowsupportmultiplewindowsystems限制條件:minimizewindowsystemdependenciesinapplication&frameworkcodelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第33頁(yè)。342.6支持多種窗口系統(tǒng)是否可以用AbstractFactory模式?EachGUIlibrarywilldefineitsownconcreteclasses.無法給每種窗口組件都創(chuàng)建一個(gè)公共抽象產(chǎn)品類StartwithanabstractWindowhierarchyuser-levelwindowabstractiondisplaysaglyph(structure)windowsystem-independenttask-relatedsubclasses
(e.g.,IconWindow,PopupWindow)lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第34頁(yè)。35classWindow{public:...voidiconify();//window-managementvoidraise();...voiddrawLine(...);//device-independentvoiddrawText(...);//graphicsinterface...};WindowInterfacelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第35頁(yè)。36Window實(shí)現(xiàn)DefinedinterfaceLexidealswith,butwheredoestherealwindowinglibrarycomeintoit?CoulddefinealternateWindowclasses&subclasses.AtbuildtimecansubstitutetheappropriateoneCouldsubclasstheWindowhierarchy.Bridgelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第36頁(yè)。37Window實(shí)現(xiàn)代碼示例publicclassRectangleextendsGlyph{publicvoiddraw(Windoww){w.drawRect(x0,y0,x1,y1);}...}publicclassWindow{publicvoiddrawRect(Coordx0,y0,x1,y1){imp.drawRect(x0,y0,x1,y1);}...}publicclassXWindowImpextendsWindowImp{publicvoiddrawRect(Coordx0,y0,x1,y1){...XDrawRectangle(display,windowId,graphics,x,y,w,h);}}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第37頁(yè)。38配置‘imp’publicabstractclassWindowSystemFactory{publicabstractWindowImpcreateWindowImp();publicabstractColorImpcreateColorImp();...}publicclassXWindowSystemFactoryextendsWindowSystemFactory{publicWIndowImpcreateWindowImp(){returnnewXWindowImp();}...}publicclassWindow{Window(){imp=windowSystemFactory.createWindowImp();}...}AbstractFactorywell-knownobjectlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第38頁(yè)。39對(duì)象結(jié)構(gòu)
Note:thedecouplingbetweenthelogicalstructureofthecontentsinawindowfromthephysicalrenderingofthecontentsinthewindowlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第39頁(yè)。40BRIDGE模式
objectstructural意圖separatea(logical)abstractioninterfacefromits(physical)implementation(s)適用性wheninterface&implementationshouldvaryindependentlyrequireauniforminterfacetointerchangeableclasshierarchiesStructurelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第40頁(yè)。41BRIDGE模式(cont’d)objectstructural效果abstractioninterface&implementationareindependentimplementationscanvarydynamicallyone-size-fits-allAbstraction&Implementorinterfaces實(shí)現(xiàn)sharingImplementors&referencecountingcreatingtherightimplementorlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第41頁(yè)。422.7用戶操作Operationscreatenew,save,cut,paste,quit,…UImechanismsmousing&typinginthedocumentpull-downmenus,pop-upmenus,buttons,kbdaccelerators,…Wishtode-coupleoperationsfromUImechanismre-usesamemechanismformanyoperationsre-usesameoperationbymanymechanismsOperationshavemanydifferentclasseswishtode-coupleknowledgeoftheseclassesfromtheUIWishtosupportmulti-levelundoandredolexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第42頁(yè)。43CommandsAbuttonorapull-downmenuisjustaGlyph.buthaveactionscommandassociatedwithuserinpute.g.,MenuItemextendsGlyph,ButtonextendsGlyph,…Could…PageFwdMenuItemextendsMenuItemPageFwdButtonextendsButtonCould…HaveaMenuItemattributewhichisafunctioncall.沒有強(qiáng)調(diào)撤銷/重做操作很難將狀態(tài)和函數(shù)聯(lián)系起來函數(shù)很難擴(kuò)充,并且很難部分復(fù)用。Will…HaveaMenuItemattributewhichisacommandobject.lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第43頁(yè)。44Command:EncapsulateEachRequest
ACommandencapsulatesCommandmayimplementtheoperationsitself,ordelegatethemtootherobject(s)anoperation(execute())aninverseoperation(unexecute())aoperationfortestingreversibility
(boolean
reversible())statefor(un)doingtheoperationlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第44頁(yè)。45Command類層次Commandisanabstractclassforissuingrequests.lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第45頁(yè)。46MenuItem與Command之間的關(guān)系voidMenuItem::clicked(){
command->execute();
}voidPasteCommand::execute(){
//dothepaste
}voidCopyCommand::execute(){
//dothecopy
}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第46頁(yè)。47InvokingCommandsWhenaninteractiveGlyphistickled,itcallstheCommandobjectwithwhichithasbeeninitialized.Commandlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第47頁(yè)。48Undo/RedoAddanunexecute()methodtoCommandReversestheeffectsofaprecedingexecute()operationusingwhateverundoinformationexecute()storedintotheCommandobject.AddaisUndoable()andahadnoEffect()methodMaintainCommandhistory:lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第48頁(yè)。49COMMAND模式
objectbehavioral意圖encapsulatetherequestforaservice適用性toparameterizeobjectswithanactiontoperformformultilevelundo/redoStructurelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第49頁(yè)。50COMMAND模式(cont’d)objectbehavioral效果abstractsexecutorofaservicesupportsarbitrary-levelundo-redocompositionyieldsmacro-commandsmightresultinlotsoftrivialcommandsubclasseslexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第50頁(yè)。512.8拼寫檢查和斷字處理Textualanalysischeckingformisspellingsintroducinghyphenationpointswhereneededforgoodformatting.Wanttosupportmultiplealgorithms.Wanttomakeiteasytoaddnewalgorithms.WanttomakeiteasytoaddnewtypesoftextualanalysiswordcountgrammarLegibility(易讀性)Wishtode-coupletextualanalysisfromtheGlyphclasses.lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第51頁(yè)。522.8拼寫檢查和斷字處理目標(biāo):analyzetextforspellingerrorsintroducepotentialhyphenation(斷字)sites限制條件:supportmultiplealgorithmsdon’ttightlycouplealgorithmswithdocumentstructurelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第52頁(yè)。53AccessingScatteredInformationNeedtoaccessthetextletter-by-letter.OurdesignhastextscatteredallovertheGlyphhierarchy.DifferentGlyphshavedifferentdatastructuresforstoringtheirchildren(lists,trees,arrays,…).Sometimesneedalternateaccesspatterns:spellcheck:forwardsearchback:backwardsevaluatingequations:inordertreetraversallexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第53頁(yè)。54EncapsulatingAccess&TraversalsCouldreplaceindex-orientedaccess(asshownbefore)bymoregeneralaccessorsthataren’tbiasedtowardsarrays.Glyphg=…for(g.first(PREORDER);!g.done();g->next()){Glyphcurrent=g->getCurrent();…}Problems:can’tsupportnewtraversalswithoutextendingenumandmodifyingallparentGlyphtypes.Can’tre-usecodetotraverseotherobjectstructures(e.g.,Commandhistory).lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第54頁(yè)。55解決方案:封裝遍歷IteratorencapsulatesatraversalalgorithmwithoutexposingrepresentationdetailstocallersusesGlyph’schildenumerationoperationThisisanexampleofa“preorderiterator”lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第55頁(yè)。56Iterator層次Iteratorlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第56頁(yè)。57UsingIteratorsGlyph*g;Iterator<Glyph*>*i=g->CreateIterator();for(i->First();!i->IsDone();i->Next()){Glyph*child=i->CurrentItem();//dosomethingwithcurrentchild}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第57頁(yè)。58InitializingIteratorsIterator<Glyph*>*Row::CreateIterator(){returnnewListIterator<Glyph*>(_children);}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第58頁(yè)。59ImplementingaComplexIteratorvoidPreorderIterator::First(){Iterator<Glyph*>*i=_root->CreateIterator();if(i){i->First();_iterators.RemoveAll();_iterators.Push(i);}}Glyph*PreorderIterator::CurrentItem()const{return_iterators.Size()>0?_iterators.Top()->CurrentItem():0;}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第59頁(yè)。60ImplementingaComplexIterator(cont’d)voidPreorderIterator::Next(){Iterator<Glyph*>*i=_iterators.Top()->CurrentItem()->CreateIterator();i->First();_iterators.Push(i);while(_iterators.Size()>0&&_iterators.Top()->IsDone()){delete_iterators.Pop();_iterators.Top()->Next();}}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第60頁(yè)。61ITERATOR模式
objectbehavioral意圖accesselementsofacontainerwithoutexposingitsrepresentation適用性requiremultipletraversalalgorithmsoveracontainerrequireauniformtraversalinterfaceoverdifferentcontainerswhencontainerclasses&traversalalgorithmmustvaryindependentlyStructurelexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第61頁(yè)。62ITERATOR模式
(cont’d)objectbehavioral效果flexibility:aggregate&traversalareindependentmultipleiterators&multipletraversalalgorithmsadditionalcommunicationoverheadbetweeniterator&aggregate實(shí)現(xiàn)internalversusexternaliteratorsviolatingtheobjectstructure’sencapsulationrobustiteratorslexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第62頁(yè)。63ITERATOR
模式(cont’d)objectbehavioralintmain(intargc,char*argv[]){vector<string>args;for(inti=0;i<argc;i++) args.push_back(string(argv[i]));for(vector<string>::iteratori(args.begin());i!=args.end();i++)cout<<*i;cout<<endl;return0;}IteratorsareusedheavilyintheC++StandardTemplateLibrary(STL)ThesameiteratorpatterncanbeappliedtoanySTLcontainer!lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第63頁(yè)。64訪問動(dòng)作Nowthatwecantraverse,weneedtoaddactionswhiletraversingthathavestatespelling,hyphenation,…CouldaugmenttheIteratorclasses……butthatwouldreducetheirreusabilityCouldaugmenttheGlyphclasses……butwillneedtochangeGlyphclassesforeachnewanalysisWillneedtoencapsulatetheanalysisinaseparateobjectlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第64頁(yè)。65Visitordefinesaction(s)ateachstepoftraversalavoidswiringaction(s)intoGlyphsiteratorcallsglyph’saccept(Visitor)ateachnodeaccept()callsbackonvisitor(aformof“staticpolymorphism”basedonmethodoverloadingbytype)voidCharacter::accept(Visitor&v){v.visit(*this);}classVisitor{public:virtualvoidvisit(Character&);virtualvoidvisit(Rectangle&);virtualvoidvisit(Row&);//etc.forallrelevantGlyphsubclasses
};lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第65頁(yè)。66ActionsinIteratorsIteratorwillcarrytheanalysisobjectalongwithitasititerates.Theanalyzerwillaccumulatestate.e.g.,charactersforaspellchecklexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第66頁(yè)。67AvoidingDowncastsHowcantheanalysisobjectdistinguishdifferentkindsofGlyphswithoutresortingtoswitchstatementsanddowncasts.e.g.,avoid:publicclassSpellingCheckerextends…{publicvoidcheck(Glyphg){if(ginstanceofCharacterGlyph){CharacterGlyphcg=(CharacterGlyph)g;//analyzethecharacter}elseif(ginstanceofRowGlyph){rowGlyphrg=(RowGlyph)g;//preparetoanalyzethechildglyphs}else…}}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第67頁(yè)。68AcceptingVisitorspublicabstractclassGlyph{publicabstractvoidaccept(Visitorv);…}publicclassCharacterGlyphextendsGlyph{publicvoidaccept(Visitorv){v.visitCharacterGlyph(this);}…}lexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第68頁(yè)。69Visitor&SubclassespublicabstractclassVisitor{publicvoidvisitCharacterGlyph(CharacterGlyphcg){/*donothing*/}publicabstractvoidvisitRowGlyph(RowGlyphrg);{/*donothing*/}…}publicclassSpellingVisitorextendsVisitor{publicvoidvisitCharacterGlyph(CharacterGlyphcg){…}}Visitorlexi設(shè)計(jì)案例分析全文共76頁(yè),當(dāng)前為第69頁(yè)。70SpellingVisitorpublicclassSpellingVisitorextendsVisitor{privateVectormisspellings=newVector();privateStringcurrentWord=“”;publicvoidvisitCharacterGlyph(CharacterGlyphcg){charc=cg->get
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- pivas耗材管理制度
- 企業(yè)設(shè)備故障管理制度
- ktv酒吧倉(cāng)庫(kù)管理制度
- 客房操作間管理制度
- 清單制安全管理制度
- 外加劑安全管理制度
- 唐朝在教育管理制度
- 水面保潔船管理制度
- 總經(jīng)辦流程管理制度
- 教師任命與管理制度
- 通信員工安全試題及答案
- 2025年洗紋身協(xié)議書
- 工會(huì)廠務(wù)公開課件
- 桃花源記的試題及答案
- 工廠計(jì)件獎(jiǎng)罰管理制度
- 2024年陜西省西安市初中學(xué)業(yè)水平模擬考試地理試卷
- 2025黑龍江省交通投資集團(tuán)限公司招聘348人易考易錯(cuò)模擬試題(共500題)試卷后附參考答案
- cpsm考試試題及答案
- 匯川技術(shù)高壓變頻器技術(shù)標(biāo)準(zhǔn)教材
- 2025年玻璃鋼圍網(wǎng)漁船項(xiàng)目市場(chǎng)調(diào)查研究報(bào)告
- 江蘇省南京2022年中考?xì)v史試卷(解析版)
評(píng)論
0/150
提交評(píng)論