如何學(xué)習(xí)(面向?qū)ο蟮?軟件分析設(shè)計(jì)_第1頁(yè)
如何學(xué)習(xí)(面向?qū)ο蟮?軟件分析設(shè)計(jì)_第2頁(yè)
如何學(xué)習(xí)(面向?qū)ο蟮?軟件分析設(shè)計(jì)_第3頁(yè)
如何學(xué)習(xí)(面向?qū)ο蟮?軟件分析設(shè)計(jì)_第4頁(yè)
如何學(xué)習(xí)(面向?qū)ο蟮?軟件分析設(shè)計(jì)_第5頁(yè)
已閱讀5頁(yè),還剩201頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

DesignPatterns1InstituteofComputerSoftwareNanjingUniversityOutlineIntroductionOODesignbyexamplesAcontrastingexampleUsageofInheritance:“Undo”mechanismDesignPatterns(esp.GoFpatterns)Why,What,HowCreational,StructuralandBehavioralPatternsSummary2InstituteofComputerSoftwareIntroduction如何學(xué)習(xí)(面向?qū)ο蟮模┸浖治鲈O(shè)計(jì)?本質(zhì)上是一種“能力”可“學(xué)”難“教”Intheorypracticeisthesameastheory.

Inpracticeitisn't.

--AdamSmith紙上得來終覺淺,絕知此事要躬行。

——冬夜讀書示子聿(陸游·宋)吾生也有涯,而知也無涯。

——《莊子》3InstituteofComputerSoftwareIntroduction學(xué)習(xí)OO軟件設(shè)計(jì)從程序設(shè)計(jì)開始建立對(duì)象計(jì)算基本概念;從程序組織到運(yùn)行機(jī)制;知道什么樣的結(jié)構(gòu)可以被有效/高效實(shí)現(xiàn);知道什么對(duì)設(shè)計(jì)變動(dòng)敏感,什么不敏感;學(xué)習(xí)前人經(jīng)驗(yàn)!設(shè)計(jì)模式--解決反復(fù)出現(xiàn)的問題的設(shè)計(jì)經(jīng)驗(yàn)4InstituteofComputerSoftwareExample1:

Multi-panelinteractivesystemsTheproblemSimple-mindedsolutionFunctional,top-downsolutionObject-orientedsolutionDiscussion5InstituteofComputerSoftwareExample1:

Multi-panelinteractivesystemsTheproblem業(yè)務(wù)流程每個(gè)會(huì)話(session)須經(jīng)歷多個(gè)步驟當(dāng)前步驟顯示panel(對(duì)話框),獲取用戶輸入(選擇),若輸入錯(cuò),給提示,直至正確;依據(jù)輸入進(jìn)行處理并轉(zhuǎn)入下一步驟(轉(zhuǎn)入哪個(gè)步驟可能依賴于用戶的輸入);對(duì)話界面例如航空訂票6InstituteofComputerSoftware7InstituteofComputerSoftware狀態(tài)轉(zhuǎn)換圖8InstituteofComputerSoftware設(shè)計(jì)要點(diǎn)圖可能很大圖可能變化要考慮復(fù)用軟件設(shè)計(jì)之難在于多種(可能沖突)的需求之間的均衡取舍9InstituteofComputerSoftwareExample1:

ASimple-mindedsolution10InstituteofComputerSoftwareExample1:

ASimple-mindedsolution問題“Goto”!本質(zhì):轉(zhuǎn)換圖結(jié)構(gòu)分散地hardwired到各個(gè)模塊的算法中若增加狀態(tài)或改動(dòng)流程?如何復(fù)用?11InstituteofComputerSoftwareExample1:

Afunctional,top-downsolution好,我們消除goto,并將流程獨(dú)立出來,放到一個(gè)函數(shù)中

transition(state,choice)

12InstituteofComputerSoftware13InstituteofComputerSoftwareTop-downdecomposition14InstituteofComputerSoftwareThetop15InstituteofComputerSoftware16InstituteofComputerSoftwareCritique17InstituteofComputerSoftware18InstituteofComputerSoftwareFragileness增加狀態(tài)怎樣?Single-choiceprinciple?如何在不同應(yīng)用間復(fù)用?19InstituteofComputerSoftwareExample1:

Anobject-orientedarchitectureLawofinversionIfyourroutinesexchangetoomanydata,putyourroutinesinyourdata.20InstituteofComputerSoftwareStateasaclass21InstituteofComputerSoftware22InstituteofComputerSoftwareUseinheritanceanddeferredclass23InstituteofComputerSoftware24InstituteofComputerSoftware25InstituteofComputerSoftware26InstituteofComputerSoftware27InstituteofComputerSoftware28InstituteofComputerSoftwareThesystem?–AnADT,nota“main”function29InstituteofComputerSoftware30InstituteofComputerSoftware31InstituteofComputerSoftware32InstituteofComputerSoftware33InstituteofComputerSoftware34InstituteofComputerSoftwareExample1:

DiscussionFocusondataabstraction“Forget”the“main”functionofthesystem,resisttheconstanttemptationtoask“Whatdoesthesystemdo?”Lawofinversion“realworld”?Sapir–Whorfhypothesis35InstituteofComputerSoftwareExample2:

“Undo”inaninteractivesystemTheproblemFindingtheabstractionMulti-levelundo-redoImplementationissuesAnaturalinterfacederivedfromtheimplementationDiscussion36InstituteofComputerSoftwareExample2:

TheproblemToerrishuman.Undo…“后悔藥”Whatif…Multi-levelundoandredoAppliedeverywhereviMSWordAgeneral(i.e.reusable)solution?37InstituteofComputerSoftwareExample2:

RequirementsWidelyapplicable.Noredesignforeachnewcommand.ReasonablestorageusageMulti-levelundosupport38InstituteofComputerSoftwareExample2:

Findingtheabstraction尋找對(duì)象:對(duì)象式軟件構(gòu)造的關(guān)鍵步驟找到可以作為類的抽象概念討論Undo和Redo的核心概念?“操作命令”簡(jiǎn)稱Command,如鍵入、刪除、設(shè)置格式等等注意:“Undo”和“Redo”不屬于一般的

Commands作為對(duì)象--類--ADT操作?39InstituteofComputerSoftwaredeferred

class

COMMANDfeature executeis

deferred

end undois

deferred

endend40InstituteofComputerSoftwareclass

LINE_DELETIONinherit COMMANDfeaturedeleted_line_index:INTEGERdeleted_line:STRINGset_deleted_line_index

(n:INTEGER)is --Settonthenumberofnextlinetobedeleted.do

deleted_line_index

:=n

endexecuteis--Deleteline.do“Deletelinenumberdeleted_line_index”“Recordtextofdeletedlineindeleted_line”

endundois--Restorelastdeletedline.do “Putbackdeleted_line

atpositiondeleted_line_index”endend41InstituteofComputerSoftwareWidelyapplicableReasonableStorageUsage42InstituteofComputerSoftware“Getlatestuserrequest”“Decoderequest”if

“Requestisanormalcommand(notUndo)”then“Determinethecorrespondingcommandinoursystem”“Executethatcommand”elseif

“RequestisUndo”thenif

“Thereisacommandtobeundone”then “Undolastcommand”elseif

“Thereisacommandtoberedone”then “Redolastcommand”

endelse“Reporterroneousrequest”end43InstituteofComputerSoftwareNoredesign44InstituteofComputerSoftwareExample2:

Multi-levelundo-redoThehistory:又一個(gè)概念可以復(fù)用某些容器類型--butwhichone?ADT!requested:COMMAND

history:LIST[COMMAND]45InstituteofComputerSoftwareExample2:

Undoaniteminthehistoryifon_item

then

history.item.undo

history.backelse message("Nothingtoundo")end46InstituteofComputerSoftwareExample2:

Historyisapolymorphicdatastructure47InstituteofComputerSoftwareExample2:

AboutRedoif

not_last

then

history.forth

history.item.redoelse message("Nothingtoredo")endredois --Re-executecommandthathasbeenundone --bydefault,thesamethingasexecutingit.do executeend48InstituteofComputerSoftwareExample2:

一般命令if

not

is_last

then

remove_all_right

end

history.put

(requested) --Recallthatputinsertsatthe --endofthelistandmoves --thecursortothenewelement.requested.execute49InstituteofComputerSoftwareExample2:

ImplementationissuesCommandargumentsCOMMAND--COMMAND_INSTANCE:command_type:COMMANDArgument:ANY復(fù)用COMMAND的對(duì)象commands:ARRAY[COMMAND]以Command代碼為數(shù)組下標(biāo)50InstituteofComputerSoftware又一個(gè)多態(tài)數(shù)據(jù)結(jié)構(gòu)Java中,命令代碼可定義為枚舉類型,用它作為Key,命令對(duì)象作為

Value,構(gòu)造一個(gè)Map,例如HashTable。同樣也是多態(tài)數(shù)據(jù)結(jié)構(gòu)。51InstituteofComputerSoftwareHistoryList的實(shí)現(xiàn)52InstituteofComputerSoftwareAnaturalinterface53InstituteofComputerSoftwareAnaturalinterface54InstituteofComputerSoftwareExample2:

Discussion繼承-多態(tài)之優(yōu)雅抽象的思維具體的代碼 廣泛的復(fù)用需求-設(shè)計(jì)-實(shí)現(xiàn)之間的平滑過渡從實(shí)現(xiàn)得出的UISmallClasses?Isitagoodideatomakecommandsclasses?55InstituteofComputerSoftwareDesignPatterns:Why?直接目的:掌握解決反復(fù)出現(xiàn)的問題的辦法;溝通的手段(設(shè)計(jì)詞匯;文檔)更進(jìn)一步:從這些實(shí)踐證明是成功的設(shè)計(jì)中學(xué)習(xí)“設(shè)計(jì)”反復(fù)閱讀;反復(fù)應(yīng)用;反復(fù)揣摩。56InstituteofComputerSoftwareWhatisaDesignPattern?ChristopherAlexander: "Eachpatterndescribesaproblemwhichoccursoverandoveragaininourenvironment,andthendescribesthecoreofthesolutiontothatproblem,insuchawaythatyoucanusethissolutionamilliontimesover,withouteverdoingitthesamewaytwice"

本質(zhì)上是設(shè)計(jì)經(jīng)驗(yàn)的文檔化。57InstituteofComputerSoftwareEssentialelementsPatternnameName,Classification,Intent,AlsoknownasProblemMotivation,ApplicabilitySolutionStructure,Participants,CollaborationImplementation,Sample

Code,Known

usesConsequencesConsequences,Related

pattern58InstituteofComputerSoftware軟件設(shè)計(jì)模式Descriptionofcommunicatingobjectsandclassesthatarecustomizedtosolveageneraldesignprobleminaparticularcontext.59InstituteofComputerSoftware模式分類GangofFour的分類Creational,Structural,BehavioralPOSAArchitecturalpattern,Designpattern,Idioms60InstituteofComputerSoftwareCreationalPatterns構(gòu)造函數(shù)無法多態(tài)允引可導(dǎo)致類間耦合;基于接口的解耦;但怎樣創(chuàng)建對(duì)象?如何在對(duì)象構(gòu)造的環(huán)節(jié)上提供足夠的靈活性?要構(gòu)造某對(duì)象的Client代碼設(shè)計(jì)時(shí),不知道該待構(gòu)造對(duì)象的具體的類61InstituteofComputerSoftwareAbstractFactory(Kit)Intent“Provideaninterfaceforcreatingfamiliesofrelatedordependentobjectswithoutspecifyingtheirconcreteclasses.”MotivationJFCSwingLook&Feel為保證視感風(fēng)格標(biāo)準(zhǔn)間的可移植性,應(yīng)用不應(yīng)該為一個(gè)特定的視感外觀硬編碼它的窗口組件。在整個(gè)應(yīng)用中實(shí)例化特定視感風(fēng)格的窗口組件類將使得以后很難改變視感風(fēng)格。62InstituteofComputerSoftwareMotivation定義一個(gè)抽象的WidgetFactory類,聲明一個(gè)用來創(chuàng)建每一種基本窗口組件的接口。每一種窗口組件都有一個(gè)抽象類,而具體子類則實(shí)現(xiàn)了窗口組件的特定視感風(fēng)格。對(duì)于每一個(gè)抽象窗口組件類,WidgetFactory接口都有一個(gè)返回新窗口組件對(duì)象的操作。客戶調(diào)用這些操作以獲得窗口組件實(shí)例,但客戶并不知道他們正在使用的是哪些具體類63InstituteofComputerSoftware64InstituteofComputerSoftwareApplicability一個(gè)系統(tǒng)要獨(dú)立于它的產(chǎn)品的創(chuàng)建、組合和表示時(shí)。一個(gè)系統(tǒng)要由多個(gè)產(chǎn)品系列中的一個(gè)來配置時(shí)。當(dāng)你要強(qiáng)調(diào)一系列相關(guān)的產(chǎn)品對(duì)象的設(shè)計(jì)以便進(jìn)行聯(lián)合使用時(shí)。當(dāng)你提供一個(gè)產(chǎn)品類庫(kù),而只想顯示它們的接口而不是實(shí)現(xiàn)時(shí)。65InstituteofComputerSoftwareSolutionStructure:66InstituteofComputerSoftwareParticipants:AbstractFactory(WidgetFactory)聲明創(chuàng)建抽象產(chǎn)品對(duì)象的接口。ConcreteFactory

(MotifWidgetFactory,PMWidgetFactory)實(shí)現(xiàn)創(chuàng)建具體產(chǎn)品對(duì)象的操作.AbstractProduct(Window,ScrollBar)為一種產(chǎn)品對(duì)象聲明一個(gè)接口。ConcreteProduct(MotifWindow,MotifScrollBar)定義將被相應(yīng)的具體工廠創(chuàng)建的產(chǎn)品對(duì)象。—實(shí)現(xiàn)AbstractProduct接口。Client僅使用由AbstractFactory和AbstractProduct類聲明的接口67InstituteofComputerSoftwareCollaborations通常在運(yùn)行時(shí)刻創(chuàng)建一個(gè)ConcreteFactroy類的實(shí)例。這一具體的工廠創(chuàng)建具有特定實(shí)現(xiàn)的產(chǎn)品對(duì)象。為創(chuàng)建不同的產(chǎn)品對(duì)象,客戶應(yīng)使用不同的具體工廠。AbstractFactory將產(chǎn)品對(duì)象的創(chuàng)建延遲到它的ConcreteFactory子類。68InstituteofComputerSoftwareConsequencesItisolatesconcreteclasses.Itmakesexchangingproductfamilieseasy.Itpromotesconsistencyamongproducts.Supportingnewkindsofproductsisdifficult.69InstituteofComputerSoftwareImplementationandSampleCodeKnowUseRelatedPatternsReadGoF’sbookyourselffor70InstituteofComputerSoftwareDiscussionChoseLook&Feelonceforall SingleChoicePrinciple!ChangeLook&Feeldynamicall Polymorphism.Separationofinterfaceandimplementation InterfaceInheritance71InstituteofComputerSoftware其他GoF模式以下有關(guān)設(shè)計(jì)模式的講義引自潘愛民先生的講義。有格式和些許內(nèi)容的改動(dòng)。72InstituteofComputerSoftware其他創(chuàng)建型模式FactoryMethodBuilderPrototypeSingletom73InstituteofComputerSoftwareFactoryMethod(一)Aliases:virtualconstructorIntentDefineaninterfaceforcreatinganobject,butletsubclassesdecidewhichclasstoinstantiate.FactoryMethodletsaclassdeferinstantiationtosubclasses.MotivationFrameworksuseabstractclassestodefineandmaintainrelationshipsbetweenobjects.Aframeworkisoftenresponsibleforcreatingtheseobjectsaswell.74InstituteofComputerSoftwareFactoryMethod模式(二)Applicability:UsetheFactoryMethodpatternwhenaclasscan'tanticipatetheclassofobjectsitmustcreate.aclasswantsitssubclassestospecifytheobjectsitcreates.classesdelegateresponsibilitytooneofseveralhelpersubclasses,andyouwanttolocalizetheknowledgeofwhichhelpersubclassisthedelegate.75InstituteofComputerSoftware插:virtualconstructorintent:在一個(gè)類層次中,客戶在runtime要?jiǎng)?chuàng)建一個(gè)對(duì)象,對(duì)象的子類型未確定,根據(jù)客戶的需要和環(huán)境情況,確定對(duì)象的類型problem:只知道對(duì)象的一般類型,不知道確切類型(需要從環(huán)境中獲取類型信息)Forces:隱藏對(duì)象的類型層次,只發(fā)布基接口如何確定最合適的派生類客戶必須有辦法使用派生類的服務(wù)76InstituteofComputerSoftware插:virtualconstructor(續(xù))solution:使用Envelope/Letter或者Handle/Bodypattern由envelope或者h(yuǎn)andle根據(jù)環(huán)境信息選擇適當(dāng)?shù)呐缮愋屠樱?根據(jù)stream動(dòng)態(tài)創(chuàng)建對(duì)象2COM對(duì)象77InstituteofComputerSoftwareFactoryMethod模式(三)structParticipantsProduct、ConcreteProduct、Creator、ConcreteCreator

Collaborations78InstituteofComputerSoftwareFactoryMethod模式(四)Evaluation多態(tài)性:客戶代碼可以做到與特定應(yīng)用無關(guān),適用于任何實(shí)體類缺點(diǎn):需要Creator和相應(yīng)的子類作為factorymethod的載體,如果應(yīng)用模型確實(shí)需要creator和子類存在,則很好;否則的話,需要增加一個(gè)類層次優(yōu)點(diǎn):(1)Provideshooksforsubclasses。基類為factorymethod提供缺省實(shí)現(xiàn),子類可以重寫新的實(shí)現(xiàn),也可以繼承父類的實(shí)現(xiàn)。

體現(xiàn)了:加一層間接性,增加了靈活性(2)Connectsparallelclasshierarchies79InstituteofComputerSoftwareFactoryMethod模式(五)Connectsparallelclasshierarchies80InstituteofComputerSoftwareFactoryMethod模式(六)Implementation(1)父類是否提供缺省的實(shí)現(xiàn)(2)factorymethod的參數(shù)(3)Language-specificvariantsandissuesSmallTalk,使用類型C++,使用lazyinitialization技術(shù)(4)Usingtemplatestoavoidsubclassing81InstituteofComputerSoftwareFactoryMethod模式(七)RelatedPatternsAbstractfactoryPrototypeExamples82InstituteofComputerSoftware模式三:Builder83InstituteofComputerSoftware模式三:Builder(一)IntentSeparatetheconstructionofacomplexobjectfromitsrepresentationsothatthesameconstructionprocesscancreatedifferentrepresentationsMotivation在復(fù)雜對(duì)象的構(gòu)造過程中,允許同樣的構(gòu)造過程能夠加入新的被構(gòu)造元素“結(jié)構(gòu)化構(gòu)造過程”Applicability,UsetheBuilderpatternwhenthealgorithmforcreatingacomplexobjectshouldbeindependentofthepartsthatmakeuptheobjectandhowthey'reassembled.theconstructionprocessmustallowdifferentrepresentationsfortheobjectthat'sconstructed.84InstituteofComputerSoftwareBuilder(二)StructureParticipantsDirector、Builder、ConcreteBuilder、Product85InstituteofComputerSoftwareBuilder(三)Collaborations86InstituteofComputerSoftwareBuilder(四)EvaluationItletsyouvaryaproduct'sinternalrepresentationItisolatescodeforconstructionandrepresentationItgivesyoufinercontrolovertheconstructionprocessImplementationBuilderinterface(Assemblyandconstruction)Whynoabstractclassforproducts?EmptymethodsasdefaultinBuilder.RelatedpatternsAbstractFactory區(qū)別:(1)builder重在構(gòu)造過程,最后一步返回結(jié)果;

(2)builder構(gòu)造許多復(fù)雜對(duì)象87InstituteofComputerSoftwareBuilder(五)Examplesreaders、parsers、convertersthepersistenceofOLEdocuments88InstituteofComputerSoftware模式四:Prototype(一)IntentSpecifythekindsofobjectstocreateusingaprototypicalinstance,andcreatenewobjectsbycopyingthisprototype.Motivation以一個(gè)已有的對(duì)象作為原型,通過它來創(chuàng)建新的對(duì)象。在增加新的對(duì)象的時(shí)候,新對(duì)象的細(xì)節(jié)創(chuàng)建工作由自己來負(fù)責(zé),從而使新對(duì)象的創(chuàng)建過程與框架隔離開來Applicability當(dāng)產(chǎn)品的創(chuàng)建過程要獨(dú)立于系統(tǒng)時(shí)當(dāng)產(chǎn)品的類型是在runtime時(shí)被指定的情況下避免創(chuàng)建一個(gè)與product層次平行的factory層次時(shí)89InstituteofComputerSoftwarePrototype(二)StructureParticipantsPrototype、ConcretePrototype、ClientCollaborations90InstituteofComputerSoftwarePrototype(三)EvaluationAddingandremovingproductsatrun-timeSpecifyingnewobjectsbyvaryingvalues,降低系統(tǒng)中類的數(shù)目Configuringanapplicationwithclassesdynamically要求:每一個(gè)product類都必須實(shí)現(xiàn)Clone操作對(duì)于C++語(yǔ)言特別有意義:C++的class不是first-classobjectsImplementationUsingaprototypemanagerImplementingtheCloneoperationshallowcopyversusdeepcopySave&LoadInitializingclones兩階段構(gòu)造91InstituteofComputerSoftwarePrototype(四)RelatedpatternsPrototype與AbstractFactory往往是相互競(jìng)爭(zhēng)的factorymethodExamplesDrawCli,musiceditor92InstituteofComputerSoftwareSingleton(一)IntentEnsureaclassonlyhasoneinstance,andprovideaglobalpointofaccesstoit.MotivationIt'simportantforsomeclassestohaveexactlyoneinstance.Instance-controlledclassApplicability,UsetheSingletonpatternwhentheremustbeexactlyoneinstanceofaclass,anditmustbeaccessibletoclientsfromawell-knownaccesspoint.whenthesoleinstanceshouldbeextensiblebysubclassing,andclientsshouldbeabletouseanextendedinstancewithoutmodifyingtheircode.93InstituteofComputerSoftwareSingleton(二)StructureParticipantsSingletonCollaborationsClientsaccessaSingletoninstancesolelythroughSingleton'sInstanceoperation.94InstituteofComputerSoftwareSingleton(三)EvaluationControlledaccesstosoleinstanceReducednamespace避免使用全局變量(whynot

全局靜態(tài)對(duì)象)Permitsrefinementofoperationsandrepresentation,允許子類化Permitsavariablenumberofinstances(How?)Moreflexiblethanclassoperations(staticmemberfunctionsinC++)這種思想比較適用于Object-Based中的許多情形ImplementationEnsuringauniqueinstance考慮使用lazyinitialize使用global/staticobject的缺點(diǎn)SubclassingtheSingletonclass95InstituteofComputerSoftwareSingleton(四)RelatedpatternsSingleton與其他創(chuàng)建型模式并不矛盾,可以用singleton來實(shí)現(xiàn)其他模式中的對(duì)象。包括AbstractFactory、Builder、Prototype等。

多個(gè)實(shí)例對(duì)于構(gòu)造過程往往并無意義,所以在許多情況下singleton模式比較符合應(yīng)用背景ExamplesMFC中的CWinApp派生類實(shí)例theApp……96InstituteofComputerSoftware增加模式:Finder(一)Intent利用環(huán)境信息,根據(jù)客戶的請(qǐng)求,找到已有的、符合要求的對(duì)象,返回給客戶AliasObject-retrieverMotivation在有些情況下,客戶希望連接到一個(gè)對(duì)象上,它提供一些狀態(tài)標(biāo)識(shí)信息,由Finder返回已經(jīng)被創(chuàng)建的對(duì)象,或者重新創(chuàng)建新的對(duì)象(如果當(dāng)前不存在滿足條件的對(duì)象)Applicability,UsetheFinderpatternwhen當(dāng)需要在軟件不同部分之間建立Client/Object連接時(shí)把獲取對(duì)象的過程隱藏起來viewfinder:Theapplicationdemandsusercustomizabilityoftheactionstakenwhenaparticularfileformatisencounteredinthebrowser.97InstituteofComputerSoftwareFinder(二)StructureParticipantsclient、finder、product-table、constructor、productCollaborationsclientFinderGetObjecttableconstructorproductproductproductcreateLookup98InstituteofComputerSoftwareFinder(三)Evaluation避免同樣的對(duì)象被實(shí)例化兩次,從而提高資源利用率,避免發(fā)生資源競(jìng)爭(zhēng)把連接對(duì)象的過程與客戶隔離開帶來的問題:多個(gè)客戶共享同樣的資源,如何有效管理對(duì)象的所有權(quán)?Implementation實(shí)現(xiàn)producttable以及相應(yīng)的管理設(shè)施,保證查找過程的有效性每一個(gè)product的生命周期管理如何標(biāo)識(shí)product的類型,客戶如何多態(tài)地提供狀態(tài)標(biāo)識(shí)信息Finder對(duì)象本身可以是一個(gè)singleton99InstituteofComputerSoftwareFinder(四)Relatedpatterns與Singleton的區(qū)別:singleton是一個(gè)類的單個(gè)實(shí)例;而Finder是避免相同的對(duì)象(通常是類型和狀態(tài)信息都相同)被創(chuàng)建兩次。與Prototype的區(qū)別在創(chuàng)建product子步驟中,需要與其他創(chuàng)建型模式結(jié)合使用

ExamplesmonikerinCOM在Netscape瀏覽器中,根據(jù)MIME類型,找到插件,然后創(chuàng)建view100InstituteofComputerSoftware復(fù)習(xí):creationalpattersFactoryMethod本質(zhì):用一個(gè)virtualmethod完成創(chuàng)建過程AbstractFactory一個(gè)product族的factorymethod構(gòu)成了一個(gè)factory接口Prototype通過product原型來構(gòu)造product,Clone+prototypemanagerBuilder通過一個(gè)構(gòu)造算法和builder接口把構(gòu)造過程與客戶隔離開Singleton單實(shí)例類型,如何構(gòu)造這單個(gè)實(shí)例?如何訪問這單個(gè)實(shí)例?Finder把對(duì)象的獲取過程與客戶隔離開101InstituteofComputerSoftwarecreationalpatterns小結(jié)了解每一種模式的實(shí)質(zhì)具體實(shí)現(xiàn)的時(shí)候可能會(huì)有變化情況,或者擴(kuò)展,或者退化factorymethod是基礎(chǔ),abstractfactory是它的擴(kuò)展factorymethod、abstractfactory、prototype都涉及到類層次結(jié)構(gòu)中對(duì)象的創(chuàng)建過程,有所取舍prototype需要prototypemanagerfactorymethod需要依附一個(gè)creator類abstractfactory需要一個(gè)平行的類層次根據(jù)應(yīng)用的其他需求,以及語(yǔ)言提供的便利來決定使用哪種模式102InstituteofComputerSoftwarecreationalpatterns小結(jié)(續(xù))builder往往適合于特定的結(jié)構(gòu)需要,它所針對(duì)的product比較復(fù)雜singleton有比較強(qiáng)烈的物理意義,可以用在許多細(xì)微的地方,不一定與類層次關(guān)聯(lián)finder模式需要有一定范圍內(nèi)的對(duì)象管理功能這些patterns都很常見,有時(shí)需要結(jié)合兩種或者多種模式完成系統(tǒng)中對(duì)象的構(gòu)造過程語(yǔ)言的Reflection機(jī)制的影響103InstituteofComputerSoftware結(jié)構(gòu)型模式回顧:對(duì)象式程序的組成繼承與允引(從類型和模塊兩個(gè)角度理解)兩種結(jié)構(gòu)類結(jié)構(gòu)對(duì)象結(jié)構(gòu)104InstituteofComputerSoftware結(jié)構(gòu)型模式“Toprogramistounderstand”Ana?veunderstandingcannotleadtoaprofounddesign.設(shè)計(jì)模式不光是設(shè)計(jì)技巧。它同時(shí)也是對(duì)設(shè)計(jì)者所面臨問題的深刻理解。105InstituteofComputerSoftwareStructuralPatternsAdapterBridgeComposite*Decorator

FacadeFlyweight*Proxy

106InstituteofComputerSoftwareAdapter對(duì)象式程序常常基于抽象接口,而非具體實(shí)體;a使用b未必意味a的類依據(jù)b的具體類定義而編制實(shí)體在不同情境下可有/需有不同抽象--展現(xiàn)不同側(cè)面;Adapter可使實(shí)體匹配一預(yù)定義之接口。107InstituteofComputerSoftware108InstituteofComputerSoftware模式7:Adapter(一)Aliases:WrapperIntentConverttheinterfaceofaclassintoanotherinterfaceclientsexpect.Adapterletsclassesworktogetherthatcouldn'totherwisebecauseofincompatibleinterfaces.MotivationSometimesatoolkitclassthat'sdesignedforreuseisn'treusableonlybecauseitsinterfacedoesn'tmatchthedomain-specificinterfaceanapplicationrequires.109InstituteofComputerSoftwareAdapter模式(二)Applicability:UsetheAdapterpatternwhenyouwanttouseanexistingclass,anditsinterfacedoesnotmatchtheoneyouneed.youwanttocreateareusableclassthatcooperateswithunrelatedorunforeseenclasses,thatis,classesthatdon'tnecessarilyhavecompatibleinterfaces.(objectadapteronly)youneedtouseseveralexistingsubclasses,butit'simpracticaltoadapttheirinterfacebysubclassingeveryone.Anobjectadaptercanadapttheinterfaceofitsparentclass.110InstituteofComputerSoftwareAdapter模式(三)Struct

class adapter

object adapter

111InstituteofComputerSoftwareAdapter模式(三)ParticipantsClient、Target、Adaptee、AdapterCollaborationsclassadapterobjectadapter112InstituteofComputerSoftwareAdapter模式(四)Evaluation本質(zhì)上是兩種重用模型classadapter:無法adaptadaptee的子類,但是可以重載adaptee的行為objectadapter可以adaptadaptee的所有子類HowmuchadaptingdoesAdapterdo?PluggableadaptersUsingtwo-wayadapterstoprovidetransparency針對(duì)classadapter,用多重繼承來實(shí)現(xiàn)113InstituteofComputerSoftwareAdapter模式(五)Implementation使用C++繼承機(jī)制實(shí)現(xiàn)classadapterPublictargetprivateadaptee使用內(nèi)嵌對(duì)象技術(shù)實(shí)現(xiàn)objectadapter參見JavaBeans相關(guān)討論P(yáng)luggableadapters114InstituteofComputerSoftwareAdapter模式(六)RelatedPatternsBridgeDecoratorProxyExamplesDrawCli:COleDrawObjC++STLCOM中的site115InstituteofComputerSoftwareBridge116InstituteofComputerSoftware117InstituteofComputerSoftware模式8:Bridge(一)Aliases:Handle/BodyIntentDecoupleanabstractionfromitsimplementationsothatthetwocanvaryindependentlyMotivation要做到“抽象(接口)與實(shí)現(xiàn)分離”,最常用的辦法是定義一個(gè)抽象類,然后在子類中提供實(shí)現(xiàn)。也就是說,用繼承機(jī)制達(dá)到“抽象(接口)與實(shí)現(xiàn)分離”但是這種方法不夠靈活,繼承機(jī)制把實(shí)現(xiàn)與抽象部分永久地綁定起來,要想獨(dú)立地修改、擴(kuò)展、重用抽象(接口)與實(shí)現(xiàn)都非常困難。118InstituteofComputerSoftwareBridge模式(二)Applicability:UsetheBridge

patternwhen編譯時(shí)刻無法確定抽象(接口)與實(shí)現(xiàn)之間的關(guān)系抽象部分與實(shí)現(xiàn)部分都可以通過子類化而擴(kuò)展對(duì)一個(gè)實(shí)現(xiàn)的修改不影響客戶(無須重新編譯)在C++中,對(duì)客戶完全隱瞞實(shí)現(xiàn)細(xì)節(jié)(er?)因?yàn)閿U(kuò)展的原因,需要把一個(gè)類分成兩部分,(以便靈活組合)在多個(gè)對(duì)象之間共享數(shù)據(jù),但客戶不需要知道119InstituteofComputerSoftwareBridge模式(三)StructureParticipantsClient,Abstraction,RefinedAbstraction,Implementor,ConcreteImplementorCollaborations120InstituteofComputerSoftwareBridge模式(四)Evaluation抽象部分與實(shí)現(xiàn)部分的分離,可以在運(yùn)行時(shí)刻連接起來(不同于直接的多態(tài)引用)二進(jìn)制兼容性提高可擴(kuò)充性:抽象與實(shí)現(xiàn)兩部分可以單獨(dú)擴(kuò)充對(duì)客戶隱藏實(shí)現(xiàn)細(xì)節(jié)121InstituteofComputerSoftwareBridge模式(五)ImplementationOnlyoneImplementor

退化(C++隱蔽實(shí)現(xiàn))CreatingtherightImplementorobject

如何創(chuàng)建?根據(jù)客戶環(huán)境,或者通過factorySharingimplementors資源管理:引用計(jì)數(shù)技術(shù)Usingmultipleinheritance不好122InstituteofComputerSoftwareBridge模式(六)RelatedPatternsAbstractFactory可以用來創(chuàng)建和配置Bridge模式與Adapter模式的區(qū)別Exampleshandle:文件handle、窗口handle123InstituteofComputerSoftware插:Handle/BodyclassStringRep{ friendclassString;

StringRep(constchar*s); ~StringRep();

intcount; char*rep;};classString{public: String(); String(constString&s); String&operator=(constString&s); ~String(); String(constchar*s); ....private:

StringRep*rep;};CountedHandle/Body124InstituteofComputerSoftwareBridge討論繼承表達(dá)類型精化和模塊擴(kuò)展。一個(gè)極端的情況就是表達(dá)抽象接口與具體實(shí)現(xiàn)之間的關(guān)系有時(shí)候,對(duì)于一個(gè)抽象,需在不同維度上應(yīng)用“繼承”Bridge提供了一種“松耦合”的替代選擇125InstituteofComputerSoftware模式9:Composite(一)IntentComposeobjectsintotreestructurestorepresentpart-wholehierarchies.Compositeletsclientstreatindividualobjectsandcompositionsofobjectsuniformly.Motivation一些部件對(duì)象經(jīng)過組合構(gòu)成的復(fù)合部件對(duì)象仍然具有單個(gè)部件對(duì)象的接口,這樣的復(fù)合部件對(duì)象被稱為“容器(container)”復(fù)合部件與單個(gè)部件具有同樣的接口,所有接口包含兩部分:?jiǎn)蝹€(gè)部件的功能、管理子部件的功能遞歸組合126InstituteofComputerSoftwareComposite模式(二)Applicability:UsetheCompositepatternwhenyouwanttorepresentpart-wholehierarchiesofobjects.youwantclientstobeabletoignorethedifferencebetweencompositionsofobjectsandindividualobjects.Clientswilltreatallobjectsinthecompositestructureuniformly.127InstituteofComputerSoftwareComposite模式(三)StructureParticipantsClient,Component,Leaf,CompositeCollaborations128InstituteofComputerSoftware典型的composite對(duì)象結(jié)構(gòu)129InstituteofComputerSoftwareComposite模式(四)Evaluationdefinesclasshierarchiesconsistingofprimitiveobjectsandcompositeobjects。定義了包含leaf對(duì)象和composite對(duì)象的類層次接口。——遞歸結(jié)構(gòu)makestheclientsimple。客戶一致地處理復(fù)合對(duì)象和單個(gè)對(duì)象makesiteasiertoaddnewkindsofcomponents。易于增加新類型的組件canmakeyourdesignoverlygeneral。使得系統(tǒng)過于一般化,無法限制類型的組合,可以在運(yùn)行時(shí)刻通過類型檢查加以彌補(bǔ)130InstituteofComputerSoftwareComposite模式(五)ImplementationExplicitparentreferencesSharingcomponentsMaximizingtheComponentinterfaceDeclaringthechildmanagementoperationsShouldComponentimplementalistofComponents?ChildorderingCachingtoimproveperformanceWhoshoulddeletecomponents?(容器弱引用?)What'sthebestdatastructureforstoringcomponents?131InstituteofComputerSoftwareComposite模式(六)RelatedPatternsDecorator、Flyweight、Iterator、VisitorExamples廣泛應(yīng)用于OO領(lǐng)域MFC中的CWnd組件層次:ActiveXContainer132InstituteofComputerSoftware模式10:Facade(一)IntentProvideaunifiedinterfacetoasetofinterfacesinasubsystem.Facadedefinesahigher-levelinterfacethatmakesthesubsystemeasiertouse.Motivation使系統(tǒng)的各子系統(tǒng)之間的關(guān)聯(lián)最小,引入一個(gè)facade對(duì)象,為子系統(tǒng)提供一個(gè)簡(jiǎn)單的、泛化的設(shè)施133InstituteofComputerSoftwareFacade模式(二)Applicability:UsetheFacade

patternwhen為一個(gè)復(fù)雜的子系統(tǒng)提供一個(gè)簡(jiǎn)單接口。

子系統(tǒng)往往會(huì)非常復(fù)雜,但是其接口應(yīng)該盡可能地簡(jiǎn)單,特別是對(duì)于一般用戶而言客戶與實(shí)現(xiàn)抽象功能的諸類之間存在一定的依賴性,facade可以降低這種依賴性在多個(gè)子系統(tǒng)的結(jié)構(gòu)中,使用facade模式定義子系統(tǒng)的入口點(diǎn),有助于降低各子系統(tǒng)之間的依賴性134InstituteofComputerSoftwareFacade模式(三)StructParticipantsfacade,subsystemclassesCollaborations135InstituteofComputerSoftwareFacade模式(四)Evaluation簡(jiǎn)化子系統(tǒng)的接口,方便客戶使用子系統(tǒng)化“緊耦合”為“松耦合”

——實(shí)現(xiàn)組件軟件的關(guān)鍵技術(shù)facade模式并不限制客戶直接訪問子系統(tǒng)的內(nèi)部類和對(duì)象Implementation以抽象類的形式定義facade,進(jìn)一步decouple,從而完全隔離子系統(tǒng)的細(xì)節(jié)Publicversusprivatesubsystemclasses136InstituteofComputerSoftwareFacade模式(五)RelatedPatternsfacade對(duì)象的創(chuàng)建:singleton、abstractfactoryExamplesFakeMFClibraryNetscapeBrowserCDrawView

CDrawDocMapPluginModuleMapModuleMFClibraryCDrawView

CDrawDocMDIFrameworkMapModule137InstituteofComputerSoftware模式11:FlyWeight(一)IntentUsesharingtosupportlargenumbersoffine-grainedobjectsefficiently.Motivation當(dāng)對(duì)象的粒度太小的時(shí)候,大量對(duì)象將會(huì)產(chǎn)生巨大的資源消耗,因此考慮用共享對(duì)象(flyweight)來實(shí)現(xiàn)邏輯上的大量對(duì)象。Flyweight對(duì)象可用于不同的context中,本身固有的狀態(tài)不隨context發(fā)生變化,而其他的狀態(tài)隨context而變化138InstituteofComputerSoftwareFlyWeight模式(二)Applicability:UsetheFlyWeightpatternwhenall

ofthefollowingaretrue:Anapplicationusesalargenumberofobjects.Storagecostsarehighbecauseofthesheerquantityofobjects.Mostobjectstatecanbemadeextrinsic.Manygroupsofobjectsmaybereplacedbyrelativelyfewsharedobjectsonceextrinsicstateisremoved.Theapplicationdoesn'tdependonobjectidentity.Sinceflyweightobjectsmaybeshared,identitytestswillreturntrueforconceptuallydistinctobjects.139InstituteofComputerSoftwareFlyWeight模式(三)Struct140InstituteofComputerSoftwareFlyWeight模式(四)Struct(續(xù))Participantsclient,flyweight,concreteFlyweight,FlyweightFactory,UnsharedConcreteFlyweightCollaborations141InstituteofComputerSoftwareFlyWeight模式(五)Evaluation把對(duì)象的狀態(tài)分開:intrinsicandextrinsic節(jié)約存儲(chǔ)空間:內(nèi)部狀態(tài)的共享節(jié)約了大量空間,外部狀態(tài)可通過計(jì)算獲得從而進(jìn)一步節(jié)約空間flyweight與composite結(jié)合。Flyweight為leaf節(jié)點(diǎn),并且父節(jié)點(diǎn)只能作為外部狀態(tài)ImplementationRemovingextrinsicstate,盡可能做到實(shí)時(shí)計(jì)算(通過一個(gè)小的數(shù)據(jù)結(jié)構(gòu))Managingsharedobjects,客戶不能直接實(shí)例化flyweight,必須通過管理器,例如FlyweightFactory。

flyweight的生命周期管理,引用計(jì)數(shù)和回收142InstituteofComputerSoftwareFlyWeight模式(六)RelatedPatterns與Composite模式組合可以用flyweight實(shí)現(xiàn)State和Strategy模式中的對(duì)象ExamplesExcel中cell的管理IOleItemContainer接口允許客戶發(fā)現(xiàn)每一個(gè)cell對(duì)象用flyweight實(shí)現(xiàn)cell對(duì)象——tearoff技術(shù)對(duì)狀態(tài)的有效管理是對(duì)象技術(shù)的一個(gè)進(jìn)步“DesignPatterns”中提到的文檔編輯器的例子143InstituteofComputerSoftwareStruct

溫馨提示

  • 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ì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論