簡介:軟件設(shè)計模式二,潘愛民HTTP//WWWICSTPKUEDUCN/COMPCOURSE,內(nèi)容,復(fù)習(xí)續(xù)介紹一些重要的模式STRUCTURALPATTERNSBEHAVIORALPATTERNS,復(fù)習(xí)PATTERN定義,定義特定環(huán)境中問題的成功解決方案中的靜態(tài)、動態(tài)結(jié)構(gòu),以及結(jié)構(gòu)元素相互之間的協(xié)作關(guān)系DESIGNPATTERNSREPRESENTSOLUTIONSTOPROBLEMSTHATARISEWHENDEVELOPINGSOFTWAREWITHINAPARTICULARCONTEXT關(guān)于PATTERN的研究狀況研究歷史現(xiàn)狀PATTERN與框架PATTERN的分類粒度,復(fù)習(xí)如何描述一個模式,關(guān)鍵要素DESIGNPATTERNNAME,ALIASESORALSOKNOWNASPROBLEM,INTENTORGOALFORCES,CONSTRAINTS,MOTIVATIONCONTEXT,APPLICABILITYSOLUTIONSTRUCTUREPARTICIPANTSCOLLABORATIONIMPLEMENTATIONEVALUATION,RESULTINGCONTEXT,CONSEQUENCESRELATEDPATTERNSEXAMPLES,KNOWNUSES,復(fù)習(xí)CREATIONALPATTERS,FACTORYMETHOD本質(zhì)用一個VIRTUALMETHOD完成創(chuàng)建過程ABSTRACTFACTORY一個PRODUCT族的FACTORYMETHOD構(gòu)成了一個FACTORY接口PROTOTYPE通過PRODUCT原型來構(gòu)造PRODUCT,CLONEPROTOTYPEMANAGERBUILDER通過一個構(gòu)造算法和BUILDER接口把構(gòu)造過程與客戶隔離開SINGLETON單實例類型,如何構(gòu)造這單個實例如何訪問這單個實例FINDER把對象的獲取過程與客戶隔離開,CREATIONALPATTERNS小結(jié),了解每一種模式的實質(zhì)具體實現(xiàn)的時候可能會有變化情況,或者擴展,或者退化FACTORYMETHOD是基礎(chǔ),ABSTRACTFACTORY是它的擴展FACTORYMETHOD、ABSTRACTFACTORY、PROTOTYPE都涉及到類層次結(jié)構(gòu)中對象的創(chuàng)建過程,有所取舍PROTOTYPE需要PROTOTYPEMANAGERFACTORYMETHOD需要依附一個CREATOR類ABSTRACTFACTORY需要一個平行的類層次根據(jù)應(yīng)用的其他需求,以及語言提供的便利來決定使用哪種模式,CREATIONALPATTERNS小結(jié)續(xù),BUILDER往往適合于特定的結(jié)構(gòu)需要,它所針對的PRODUCT比較復(fù)雜SINGLETON有比較強烈的物理意義,可以用在許多細(xì)微的地方,不一定與類層次關(guān)聯(lián)FINDER模式需要有一定范圍內(nèi)的對象管理功能這些PATTERNS都很常見,有時需要結(jié)合兩種或者多種模式完成系統(tǒng)中對象的構(gòu)造過程,STRUCTURALPATTERNS,ADAPTERBRIDGECOMPOSITEDECORATORFACADEFLYWEIGHTPROXY,模式7ADAPTER一,ALIASESWRAPPERINTENTCONVERTTHEINTERFACEOFACLASSINTOANOTHERINTERFACECLIENTSEXPECTADAPTERLETSCLASSESWORKTOGETHERTHATCOULDNTOTHERWISEBECAUSEOFINCOMPATIBLEINTERFACESMOTIVATIONSOMETIMESATOOLKITCLASSTHATSDESIGNEDFORREUSEISNTREUSABLEONLYBECAUSEITSINTERFACEDOESNTMATCHTHEDOMAINSPECIFICINTERFACEANAPPLICATIONREQUIRES,ADAPTER模式二,APPLICABILITYUSETHEADAPTERPATTERNWHENYOUWANTTOUSEANEXISTINGCLASS,ANDITSINTERFACEDOESNOTMATCHTHEONEYOUNEEDYOUWANTTOCREATEAREUSABLECLASSTHATCOOPERATESWITHUNRELATEDORUNFORESEENCLASSES,THATIS,CLASSESTHATDONTNECESSARILYHAVECOMPATIBLEINTERFACESOBJECTADAPTERONLYYOUNEEDTOUSESEVERALEXISTINGSUBCLASSES,BUTITSIMPRACTICALTOADAPTTHEIRINTERFACEBYSUBCLASSINGEVERYONEANOBJECTADAPTERCANADAPTTHEINTERFACEOFITSPARENTCLASS,ADAPTER模式三,STRUCTCLASSADAPTEROBJECTADAPTER,ADAPTER模式三,PARTICIPANTSCLIENT、TARGET、ADAPTEE、ADAPTERCOLLABORATIONSCLASSADAPTERDELEGATIONOBJECTADAPTERCONTAINER,ADAPTER模式四,EVALUATION本質(zhì)上是兩種重用模型CLASSADAPTER無法ADAPTADAPTEE的子類,但是可以重載ADAPTEE的行為OBJECTADAPTER可以ADAPTADAPTEE的所有子類HOWMUCHADAPTINGDOESADAPTERDOPLUGGABLEADAPTERSUSINGTWOWAYADAPTERSTOPROVIDETRANSPARENCY針對CLASSADAPTER,用多重繼承來實現(xiàn),ADAPTER模式五,IMPLEMENTATION使用C繼承機制實現(xiàn)CLASSADAPTER使用內(nèi)嵌對象技術(shù)實現(xiàn)OBJECTADAPTERPLUGGABLEADAPTERS,三種實現(xiàn)方案使用抽象方法定義使用代理對象參數(shù)化技術(shù)這三種方法的實質(zhì)如何在一個類中定義抽象操作,供客戶插入HOOK技術(shù),ADAPTER模式六,RELATEDPATTERNSBRIDGEDECORATORPROXYEXAMPLESDRAWCLICOLEDRAWOBJCSTLCOM中的SITE,模式8BRIDGE一,ALIASESHANDLE/BODYINTENTDECOUPLEANABSTRACTIONFROMITSIMPLEMENTATIONSOTHATTHETWOCANVARYINDEPENDENTLYMOTIVATION要做到“抽象接口與實現(xiàn)分離”,最常用的辦法是定義一個抽象類,然后在子類中提供實現(xiàn)。也就是說,用繼承機制達到“抽象接口與實現(xiàn)分離”但是這種方法不夠靈活,繼承機制把實現(xiàn)與抽象部分永久地綁定起來,要想獨立地修改、擴展、重用抽象接口與實現(xiàn)都非常困難。,BRIDGE模式二,APPLICABILITYUSETHEBRIDGEPATTERNWHEN編譯時刻無法確定抽象接口與實現(xiàn)之間的關(guān)系抽象部分與實現(xiàn)部分都可以通過子類化而擴展對一個實現(xiàn)的修改不影響客戶無須重新編譯在C中,對客戶完全隱瞞實現(xiàn)細(xì)節(jié)因為擴展的原因,需要把一個類分成兩部分,以便靈活組合在多個對象之間共享數(shù)據(jù),但客戶不需要知道,BRIDGE模式三,STRUCTPARTICIPANTSCLIENT,ABSTRACTION,REFINEDABSTRACTION,IMPLEMENTOR,CONCRETEIMPLEMENTORCOLLABORATIONS,BRIDGE模式四,EVALUATION抽象部分與實現(xiàn)部分的分離,可以在運行時刻連接起來二進制兼容性提高可擴充性抽象與實現(xiàn)兩部分可以單獨擴充對客戶隱藏實現(xiàn)細(xì)節(jié),BRIDGE模式五,IMPLEMENTATIONONLYONEIMPLEMENTORCREATINGTHERIGHTIMPLEMENTOROBJECT如何創(chuàng)建根據(jù)客戶環(huán)境,或者通過FACTORYSHARINGIMPLEMENTORS資源管理引用計數(shù)技術(shù)USINGMULTIPLEINHERITANCE,BRIDGE模式六,RELATEDPATTERNSABSTRACTFACTORY可以用來創(chuàng)建和配置BRIDGE模式與ADAPTER模式的區(qū)別EXAMPLESHANDLE文件HANDLE、窗口HANDLE,插HANDLE/BODY,CLASSSTRINGREP{FRIENDCLASSSTRINGSTRINGREPCONSTCHARSSTRINGREPINTCOUNTCHARREP}CLASSSTRING{PUBLICSTRINGSTRINGCONSTSTRINGSTRINGSTRINGSTRINGCONSTCHARSPRIVATESTRINGREPREP},COUNTEDHANDLE/BODY,模式9COMPOSITE一,INTENTCOMPOSEOBJECTSINTOTREESTRUCTURESTOREPRESENTPARTWHOLEHIERARCHIESCOMPOSITELETSCLIENTSTREATINDIVIDUALOBJECTSANDCOMPOSITIONSOFOBJECTSUNIFORMLYMOTIVATION一些部件對象經(jīng)過組合構(gòu)成的復(fù)合部件對象仍然具有單個部件對象的接口,這樣的復(fù)合部件對象被稱為“容器CONTAINER”復(fù)合部件與單個部件具有同樣的接口,所有接口包含兩部分單個部件的功能、管理子部件的功能遞歸組合,COMPOSITE模式二,APPLICABILITYUSETHECOMPOSITEPATTERNWHENYOUWANTTOREPRESENTPARTWHOLEHIERARCHIESOFOBJECTSYOUWANTCLIENTSTOBEABLETOIGNORETHEDIFFERENCEBETWEENCOMPOSITIONSOFOBJECTSANDINDIVIDUALOBJECTSCLIENTSWILLTREATALLOBJECTSINTHECOMPOSITESTRUCTUREUNIFORMLY,COMPOSITE模式三,STRUCTPARTICIPANTSCLIENT,COMPONENT,LEAF,COMPOSITECOLLABORATIONS,典型的COMPOSITE對象結(jié)構(gòu),COMPOSITE模式四,EVALUATIONDEFINESCLASSHIERARCHIESCONSISTINGOFPRIMITIVEOBJECTSANDCOMPOSITEOBJECTS。定義了包含LEAF對象和COMPOSITE對象的類層次接口。遞歸結(jié)構(gòu)MAKESTHECLIENTSIMPLE??蛻粢恢碌靥幚韽?fù)合對象和單個對象MAKESITEASIERTOADDNEWKINDSOFCOMPONENTS。易于增加新類型的組件CANMAKEYOURDESIGNOVERLYGENERAL。使得系統(tǒng)過于一般化,無法限制類型的組合,可以在運行時刻通過類型檢查加以彌補,COMPOSITE模式五,IMPLEMENTATIONEXPLICITPARENTREFERENCESSHARINGCOMPONENTSMAXIMIZINGTHECOMPONENTINTERFACEDECLARINGTHECHILDMANAGEMENTOPERATIONSSHOULDCOMPONENTIMPLEMENTALISTOFCOMPONENTSCHILDORDERINGCACHINGTOIMPROVEPERFORMANCEWHOSHOULDDELETECOMPONENTSWHATSTHEBESTDATASTRUCTUREFORSTORINGCOMPONENTS,COMPOSITE模式六,RELATEDPATTERNSDECORATOR、FLYWEIGHT、ITERATOR、VISITOREXAMPLES廣泛應(yīng)用于OO領(lǐng)域MFC中的CWND組件層次ACTIVEXCONTAINER,模式10FACADE一,INTENTPROVIDEAUNIFIEDINTERFACETOASETOFINTERFACESINASUBSYSTEMFACADEDEFINESAHIGHERLEVELINTERFACETHATMAKESTHESUBSYSTEMEASIERTOUSEMOTIVATION使系統(tǒng)的各子系統(tǒng)之間的關(guān)聯(lián)最小,引入一個FACADE對象,為子系統(tǒng)提供一個簡單的、泛化的設(shè)施,FACADE模式二,APPLICABILITYUSETHEFACADEPATTERNWHEN為一個復(fù)雜的子系統(tǒng)提供一個簡單接口時。子系統(tǒng)往往會非常復(fù)雜,但是其接口應(yīng)該盡可能地簡單,特別是對于一般用戶而言客戶與抽象類的實現(xiàn)部分之間必然存在一定的依賴性,F(xiàn)ACADE可以降低這種依賴性在多個子系統(tǒng)的結(jié)構(gòu)中,使用FACADE模式定義子系統(tǒng)的入口點,有助于降低各子系統(tǒng)之間的依賴性,FACADE模式三,STRUCTPARTICIPANTSFACADE,SUBSYSTEMCLASSESCOLLABORATIONS,FACADE模式四,EVALUATION簡化子系統(tǒng)的接口,方便客戶使用子系統(tǒng)化“緊耦合”為“松耦合”實現(xiàn)組件軟件的關(guān)鍵技術(shù)FACADE模式并不限制客戶直接訪問子系統(tǒng)的內(nèi)部類和對象IMPLEMENTATION以抽象類的形式定義FACADE,進一步DECOUPLE,從而完全隔離子系統(tǒng)的細(xì)節(jié)PUBLICVERSUSPRIVATESUBSYSTEMCLASSES,FACADE模式五,RELATEDPATTERNSFACADE對象的創(chuàng)建SINGLETON、ABSTRACTFACTORYEXAMPLES,模式11FLYWEIGHT一,INTENTUSESHARINGTOSUPPORTLARGENUMBERSOFFINEGRAINEDOBJECTSEFFICIENTLYMOTIVATION當(dāng)對象的粒度太小的時候,大量對象將會產(chǎn)生巨大的資源消耗,因此考慮用共享對象FLYWEIGHT來實現(xiàn)邏輯上的大量對象。FLYWEIGHT對象可用于不同的CONTEXT中,本身固有的狀態(tài)不隨CONTEXT發(fā)生變化,而其他的狀態(tài)隨CONTEXT而變化,FLYWEIGHT模式二,APPLICABILITYUSETHEFLYWEIGHTPATTERNWHENALLOFTHEFOLLOWINGARETRUEANAPPLICATIONUSESALARGENUMBEROFOBJECTSSTORAGECOSTSAREHIGHBECAUSEOFTHESHEERQUANTITYOFOBJECTSMOSTOBJECTSTATECANBEMADEEXTRINSICMANYGROUPSOFOBJECTSMAYBEREPLACEDBYRELATIVELYFEWSHAREDOBJECTSONCEEXTRINSICSTATEISREMOVEDTHEAPPLICATIONDOESNTDEPENDONOBJECTIDENTITYSINCEFLYWEIGHTOBJECTSMAYBESHARED,IDENTITYTESTSWILLRETURNTRUEFORCONCEPTUALLYDISTINCTOBJECTS,FLYWEIGHT模式三,STRUCT,FLYWEIGHT模式四,STRUCT續(xù)PARTICIPANTSCLIENT,FLYWEIGHT,CONCRETEFLYWEIGHT,FLYWEIGHTFACTORY,UNSHAREDCONCRETEFLYWEIGHTCOLLABORATIONS,FLYWEIGHT模式五,EVALUATION把對象的狀態(tài)分開INTRINSICANDEXTRINSIC節(jié)約存儲空間內(nèi)部狀態(tài)的共享節(jié)約了大量空間,外部狀態(tài)可通過計算獲得從而進一步節(jié)約空間FLYWEIGHT與COMPOSITE結(jié)合。FLYWEIGHT為LEAF節(jié)點,并且父節(jié)點只能作為外部狀態(tài)IMPLEMENTATIONREMOVINGEXTRINSICSTATE,盡可能做到實時計算通過一個小的數(shù)據(jù)結(jié)構(gòu)MANAGINGSHAREDOBJECTS,客戶不能直接實例化FLYWEIGHT,必須通過管理器,例如FLYWEIGHTFACTORY。FLYWEIGHT的生命周期管理,引用計數(shù)和回收,FLYWEIGHT模式六,RELATEDPATTERNS與COMPOSITE模式組合可以用FLYWEIGHT實現(xiàn)STATE和STRATEGY模式中的對象EXAMPLESEXCEL中CELL的管理IOLEITEMCONTAINER接口允許客戶發(fā)現(xiàn)每一個CELL對象用FLYWEIGHT實現(xiàn)CELL對象TEAROFF技術(shù)對狀態(tài)的有效管理是對象技術(shù)的一個進步“DESIGNPATTERNS”中提到的文檔編輯器的例子,STRUCTURALPATTERNSDECORATOR,STRUCTURALPATTERNSPROXY,STRUCTURALPATTERNS小結(jié),ADAPTER、BRIDGE、FACADEADAPTER用于兩個不兼容接口之間的轉(zhuǎn)接BRIDGE用于將一個抽象與多個可能的實現(xiàn)連接起來FACADE用于為復(fù)雜的子系統(tǒng)定義一個新的簡單易用的接口COMPOSITE、DECORATOR和PROXYCOMPOSITE用于構(gòu)造對象組合結(jié)構(gòu)DECORATOR用于為對象增加新的職責(zé)PROXY為目標(biāo)對象提供一個替代者FLYWEIGHT針對細(xì)粒度對象的一種全局控制手段,BEHAVIORALPATTERNS,CHAINOFRESPONSIBILITYCOMMANDINTERPRETERITERATORMEDIATORMEMENTOOBSERVERSTATESTRATEGYTEMPLATEMETHODVISITOR,模式12COMMAND一,ALIASESACTION,TRANSACTIONFUNCTORFUNCTIONOBJECTINTENTENCAPSULATEAREQUESTASANOBJECT,THEREBYLETTINGYOUPARAMETERIZECLIENTSWITHDIFFERENTREQUESTS,QUEUEORLOGREQUESTS,ANDSUPPORTUNDOABLEOPERATIONSMOTIVATION把請求信息和請求執(zhí)行過程封裝起來FRAMEWORK往往需要把命令請求與處理請求的對象分開,COMMAND模式可以把調(diào)用操作的對象與操作的目標(biāo)對象分開允許通過多種途徑調(diào)用同一個請求。請求的重用,COMMAND模式二,APPLICABILITYUSETHECOMMANDPATTERNWHENPARAMETERIZEOBJECTSBYANACTIONTOPERFORM,代替回調(diào)SPECIFY,QUEUE,ANDEXECUTEREQUESTSATDIFFERENTTIMESSUPPORTUNDOSUPPORTLOGGINGCHANGESSOTHATTHEYCANBEREAPPLIEDINCASEOFASYSTEMCRASHSTRUCTUREASYSTEMAROUNDHIGHLEVELOPERATIONSBUILTONPRIMITIVESOPERATIONSTRANSACTIONS,COMMAND模式三,STRUCTPARTICIPANTSCLIENT,COMMAND、CONCRETECOMMAND、INVOKER、RECEIVER,COMMAND模式四,COLLABORATIONS,COMMAND模式五,EVALUATIONCOMMANDDECOUPLESTHEOBJECTTHATINVOKESTHEOPERATIONFROMTHEONETHATKNOWSHOWTOPERFORMITCOMMANDSAREFIRSTCLASSOBJECTSTHEYCANBEMANIPULATEDANDEXTENDEDLIKEANYOTHEROBJECTYOUCANASSEMBLECOMMANDSINTOACOMPOSITECOMMANDANEXAMPLEISMACROCOMMANDITSEASYTOADDNEWCOMMANDS,BECAUSEYOUDONTHAVETOCHANGEEXISTINGCLASSESIMPLEMENTATIONHOWINTELLIGENTSHOULDACOMMANDBESUPPORTINGUNDOANDREDOAVOIDINGERRORACCUMULATIONINTHEUNDOPROCESSUSINGCTEMPLATES,COMMAND模式六,RELATEDPATTERNSCOMPOSITE模式可用來實現(xiàn)COMMAND組合為實現(xiàn)UNDO/REDO,可以用其他行為模式來管理狀態(tài),如MEMENTO模式。COMMAND被放到HISTORYLIST之前,可以用PROTOTYPE模式復(fù)制自身EXAMPLES,模式13ITERATOR一,ALIASESCURSORINTENTPROVIDEAWAYTOACCESSTHEELEMENTSOFANAGGREGATEOBJECTSEQUENTIALLYWITHOUTEXPOSINGITSUNDERLYINGREPRESENTATIONMOTIVATIONANAGGREGATEOBJECTSUCHASALISTSHOULDGIVEYOUAWAYTOACCESSITSELEMENTSWITHOUTEXPOSINGITSINTERNALSTRUCTURESEPARATINGTHETRAVERSALMECHANISMFROMTHELISTOBJECTLETSUSDEFINEITERATORSFORDIFFERENTTRAVERSALPOLICIESWITHOUTENUMERATINGTHEMINTHELISTINTERFACE,ITERATOR模式二,APPLICABILITYUSETHEITERATORPATTERNWHENTOACCESSANAGGREGATEOBJECTSCONTENTSWITHOUTEXPOSINGITSINTERNALREPRESENTATIONTOSUPPORTMULTIPLETRAVERSALSOFAGGREGATEOBJECTSTOPROVIDEAUNIFORMINTERFACEFORTRAVERSINGDIFFERENTAGGREGATESTRUCTURESTHATIS,TOSUPPORTPOLYMORPHICITERATION,ITERATOR模式三,STRUCTPARTICIPANTSITERATOR、CONCRETEITERATOR、AGGREGATE、CONCRETEAGGREGATECOLLABORATIONS,ITERATOR模式四,EVALUATIONITSUPPORTSVARIATIONSINTHETRAVERSALOFANAGGREGATEITERATORSSIMPLIFYTHEAGGREGATEINTERFACEMORETHANONETRAVERSALCANBEPENDINGONANAGGREGATEIMPLEMENTATION實現(xiàn)可以非常靈活WHOCONTROLSTHEITERATIONEXTERNALITERATORVERSUSINTERNALITERATORWHODEFINESTHETRAVERSALALGORITHMAGGREGATE本身定義算法CURSORMODEITERATOR定義算法ITERATOR如何訪問數(shù)據(jù)HOWROBUSTISTHEITERATOR,ITERATOR模式五,IMPLEMENTATION續(xù)ADDITIONALITERATOROPERATIONS基本操作FIRST,NEXT,ISDONE,ANDCURRENTITEMUSINGPOLYMORPHICITERATORSITERATOR資源釋放ITERATORSMAYHAVEPRIVILEGEDACCESSITERATORSFORCOMPOSITES適合于INTERNALITERATOR或者CURSOR方式的ITERATORNULLITERATORS,ITERATOR模式六,RELATEDPATTERNSCOMPOSITEITE
下載積分: 6 賞幣
上傳時間:2024-01-05
頁數(shù): 77
大?。?0.6(MB)
子文件數(shù):