版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
1、軟件設(shè)計模式(二),潘愛民http://www.icst.pku.edu.cn/CompCourse,內(nèi)容,復(fù)習(xí)續(xù):介紹一些重要的模式Structural PatternsBehavioral Patterns,復(fù)習(xí):pattern定義,定義:特定環(huán)境中問題的成功解決方案中的靜態(tài)、動態(tài)結(jié)構(gòu),以及結(jié)構(gòu)元素相互之間的協(xié)作關(guān)系Design patterns represent solutions to problems that
2、 arise when developing software within a particular context關(guān)于pattern的研究狀況研究歷史現(xiàn)狀pattern與框架pattern的分類粒度,復(fù)習(xí):如何描述一個模式,關(guān)鍵要素Design pattern name,Aliases or Also Known AsProblem,Intent or GoalForces,Constraints,Motivati
3、onContext, ApplicabilitySolution StructureParticipantsCollaborationImplementationEvaluation,Resulting Context,ConsequencesRelated Patterns Examples,Known uses,復(fù)習(xí):creational patters,Factory Method本質(zhì):用一個virtual m
4、ethod完成創(chuàng)建過程Abstract Factory一個product族的factory method構(gòu)成了一個factory接口Prototype通過product原型來構(gòu)造product,Clone+prototype managerBuilder通過一個構(gòu)造算法和builder接口把構(gòu)造過程與客戶隔離開Singleton單實例類型,如何構(gòu)造這單個實例?如何訪問這單個實例?Finder把對象的獲取過程與客戶隔離
5、開,creational patterns小結(jié),了解每一種模式的實質(zhì)具體實現(xiàn)的時候可能會有變化情況,或者擴展,或者退化factory method是基礎(chǔ),abstract factory是它的擴展factory method、abstract factory、prototype都涉及到類層次結(jié)構(gòu)中對象的創(chuàng)建過程,有所取舍prototype需要prototype managerfactory method需要依附一個creato
6、r類abstract factory需要一個平行的類層次根據(jù)應(yīng)用的其他需求,以及語言提供的便利來決定使用哪種模式,creational patterns小結(jié)(續(xù)),builder往往適合于特定的結(jié)構(gòu)需要,它所針對的product比較復(fù)雜singleton有比較強烈的物理意義,可以用在許多細微的地方,不一定與類層次關(guān)聯(lián)finder模式需要有一定范圍內(nèi)的對象管理功能這些patterns都很常見,有時需要結(jié)合兩種或者多種模式完成系統(tǒng)
7、中對象的構(gòu)造過程,Structural Patterns,Adapter Bridge Composite * Decorator Facade Flyweight * Proxy,模式 7: Adapter (一),Aliases:WrapperIntentConvert the interface of a class into another interface clients expect. Adapter le
8、ts classes work together that couldn't otherwise because of incompatible interfaces.MotivationSometimes a toolkit class that's designed for reuse isn't reusable only because its interface doesn't match
9、the domain-specific interface an application requires.,Adapter模式(二),Applicability:Use the Adapter pattern whenyou want to use an existing class, and its interface does not match the one you need.you want to create a re
10、usable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces.(object adapter only) you need to use several existing subclasses, but it's i
11、mpractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.,Adapter模式(三),Structclassadapter objectadapter,Adapter模式(三),ParticipantsClient、Targe
12、t、Adaptee、AdapterCollaborationsclass adapter —— delegationobject adapter —— container,Adapter模式(四),Evaluation本質(zhì)上是兩種重用模型class adapter:無法adapt adaptee的子類,但是可以重載adaptee的行為object adapter可以adapt adaptee的所有子類How much
13、 adapting does Adapter do? Pluggable adaptersUsing two-way adapters to provide transparency針對class adapter,用多重繼承來實現(xiàn),Adapter模式(五),Implementation使用C++繼承機制實現(xiàn)class adapter使用內(nèi)嵌對象技術(shù)實現(xiàn)object adapterPluggable adapters,三種實現(xiàn)
14、方案使用抽象方法定義使用代理對象參數(shù)化技術(shù)這三種方法的實質(zhì):如何在一個類中定義抽象操作,供客戶插入?—— hook 技術(shù),Adapter模式(六),Related PatternsBridgeDecoratorProxyExamplesDrawCli:COleDrawObjC++ STLCOM中的site,模式 8:Bridge(一),Aliases:Handle/BodyIntentDecouple an
15、 abstraction from its implementation so that the two can vary independentlyMotivation要做到“抽象(接口)與實現(xiàn)分離”,最常用的辦法是定義一個抽象類,然后在子類中提供實現(xiàn)。也就是說,用繼承機制達到“抽象(接口)與實現(xiàn)分離”但是這種方法不夠靈活,繼承機制把實現(xiàn)與抽象部分永久地綁定起來,要想獨立地修改、擴展、重用抽象(接口)與實現(xiàn)都非常困難。,Brid
16、ge模式(二),Applicability:Use the Bridge pattern when編譯時刻無法確定抽象(接口)與實現(xiàn)之間的關(guān)系抽象部分與實現(xiàn)部分都可以通過子類化而擴展對一個實現(xiàn)的修改不影響客戶(無須重新編譯)在C++中,對客戶完全隱瞞實現(xiàn)細節(jié)因為擴展的原因,需要把一個類分成兩部分,(以便靈活組合)在多個對象之間共享數(shù)據(jù),但客戶不需要知道,Bridge模式(三),StructParticipant
17、sClient, Abstraction, RefinedAbstraction, Implementor, ConcreteImplementorCollaborations,Bridge模式(四),Evaluation抽象部分與實現(xiàn)部分的分離,可以在運行時刻連接起來二進制兼容性提高可擴充性:抽象與實現(xiàn)兩部分可以單獨擴充對客戶隱藏實現(xiàn)細節(jié),Bridge模式(五),ImplementationOnly one Implem
18、entorCreating the right Implementor object如何創(chuàng)建?根據(jù)客戶環(huán)境,或者通過factorySharing implementors資源管理:引用計數(shù)技術(shù)Using multiple inheritance,Bridge模式(六),Related PatternsAbstract Factory可以用來創(chuàng)建和配置Bridge模式與Adapter模式的區(qū)別Exampleshandle
19、:文件handle、窗口handle,插:Handle/Body,class StringRep {friend class String;StringRep(const char *s);~StringRep();int count; char *rep;};class String {public:String();String(const String &s);String &a
20、mp;operator=(const String &s);~String();String(const char *s);. . . .private:StringRep *rep;};,Counted Handle/Body,模式 9:Composite(一),IntentCompose objects into tree structures to represent part-whole hier
21、archies. Composite lets clients treat individual objects and compositions of objects uniformly.Motivation一些部件對象經(jīng)過組合構(gòu)成的復(fù)合部件對象仍然具有單個部件對象的接口,這樣的復(fù)合部件對象被稱為“容器(container)”復(fù)合部件與單個部件具有同樣的接口,所有接口包含兩部分:單個部件的功能、管理子部件的功能遞歸組合,Com
22、posite模式(二),Applicability:Use the Composite pattern whenyou want to represent part-whole hierarchies of objects. you want clients to be able to ignore the difference between compositions of objects and individual objec
23、ts. Clients will treat all objects in the composite structure uniformly.,Composite模式(三),StructParticipantsClient, Component, Leaf, CompositeCollaborations,典型的composite對象結(jié)構(gòu),Composite模式(四),Evaluationdefines class
24、 hierarchies consisting of primitive objects and composite objects。定義了包含leaf對象和composite對象的類層次接口。——遞歸結(jié)構(gòu)makes the client simple。客戶一致地處理復(fù)合對象和單個對象makes it easier to add new kinds of components。易于增加新類型的組件can make your des
25、ign overly general。使得系統(tǒng)過于一般化,無法限制類型的組合,可以在運行時刻通過類型檢查加以彌補,Composite模式(五),ImplementationExplicit parent referencesSharing componentsMaximizing the Component interfaceDeclaring the child management operationsShould Com
26、ponent implement a list of Components? Child orderingCaching to improve performanceWho should delete components? What's the best data structure for storing components?,Composite模式(六),Related PatternsDecorator、Fl
27、yweight、Iterator、VisitorExamples廣泛應(yīng)用于OO領(lǐng)域MFC中的CWnd組件層次:ActiveX Container,模式 10:Facade(一),IntentProvide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes th
28、e subsystem easier to use.Motivation使系統(tǒng)的各子系統(tǒng)之間的關(guān)聯(lián)最小,引入一個facade對象,為子系統(tǒng)提供一個簡單的、泛化的設(shè)施,Facade模式(二),Applicability:Use the Facade pattern when為一個復(fù)雜的子系統(tǒng)提供一個簡單接口時。子系統(tǒng)往往會非常復(fù)雜,但是其接口應(yīng)該盡可能地簡單,特別是對于一般用戶而言客戶與抽象類的實現(xiàn)部分之間必然存在一定的依賴性,
29、facade可以降低這種依賴性在多個子系統(tǒng)的結(jié)構(gòu)中,使用facade模式定義子系統(tǒng)的入口點,有助于降低各子系統(tǒng)之間的依賴性,Facade模式(三),StructParticipantsfacade, subsystem classesCollaborations,Facade模式(四),Evaluation簡化子系統(tǒng)的接口,方便客戶使用子系統(tǒng)化“緊耦合”為“松耦合”—— 實現(xiàn)組件軟件的關(guān)鍵技術(shù)facade模式
30、并不限制客戶直接訪問子系統(tǒng)的內(nèi)部類和對象Implementation以抽象類的形式定義facade,進一步decouple,從而完全隔離子系統(tǒng)的細節(jié)Public versus private subsystem classes,Facade模式(五),Related Patternsfacade對象的創(chuàng)建:singleton、abstract factoryExamples,模式 11:FlyWeight(一),Intent
31、Use sharing to support large numbers of fine-grained objects efficiently.Motivation當(dāng)對象的粒度太小的時候,大量對象將會產(chǎn)生巨大的資源消耗,因此考慮用共享對象(flyweight)來實現(xiàn)邏輯上的大量對象。Flyweight對象可用于不同的context中,本身固有的狀態(tài)不隨context發(fā)生變化,而其他的狀態(tài)隨context而變化,FlyWeight
32、模式(二),Applicability:Use the FlyWeight pattern when all of the following are true: An application uses a large number of objects. Storage costs are high because of the sheer quantity of objects. Most object state can b
33、e made extrinsic. Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed. The application doesn't depend on object identity. Since flyweight objects may be shared, i
34、dentity tests will return true for conceptually distinct objects.,FlyWeight模式(三),Struct,FlyWeight模式(四),Struct(續(xù))Participantsclient, flyweight, concreteFlyweight, FlyweightFactory,UnsharedConcreteFlyweightCollab
35、orations,FlyWeight模式(五),Evaluation把對象的狀態(tài)分開:intrinsic and extrinsic 節(jié)約存儲空間:內(nèi)部狀態(tài)的共享節(jié)約了大量空間,外部狀態(tài)可通過計算獲得從而進一步節(jié)約空間flyweight與composite結(jié)合。Flyweight為leaf節(jié)點,并且父節(jié)點只能作為外部狀態(tài)ImplementationRemoving extrinsic state,盡可能做到實時計算(通過一個小
36、的數(shù)據(jù)結(jié)構(gòu))Managing shared objects,客戶不能直接實例化flyweight,必須通過管理器,例如FlyweightFactory。flyweight的生命周期管理,引用計數(shù)和回收,FlyWeight模式(六),Related Patterns與Composite模式組合可以用flyweight實現(xiàn)State和Strategy模式中的對象ExamplesExcel中cell的管理IOleItemCont
37、ainer接口允許客戶發(fā)現(xiàn)每一個cell對象用flyweight實現(xiàn)cell對象 —— tearoff技術(shù)對狀態(tài)的有效管理是對象技術(shù)的一個進步“Design Patterns”中提到的文檔編輯器的例子,Structural Patterns :Decorator,Structural Patterns :Proxy,Structural patterns小結(jié),Adapter 、bridge、facadeadapter用于兩個不兼
38、容接口之間的轉(zhuǎn)接bridge用于將一個抽象與多個可能的實現(xiàn)連接起來facade用于為復(fù)雜的子系統(tǒng)定義一個新的簡單易用的接口composite、decorator和proxycomposite用于構(gòu)造對象組合結(jié)構(gòu)decorator用于為對象增加新的職責(zé)proxy為目標對象提供一個替代者flyweight針對細粒度對象的一種全局控制手段,Behavioral Patterns,Chain of Responsibility
39、*Command Interpreter *Iterator Mediator *Memento *Observer State *Strategy Template Method *Visitor,模式 12:Command(一),AliasesAction, Transactionfunctor (function object)IntentEncapsulate a request as an obje
40、ct, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.Motivation把請求信息和請求執(zhí)行過程封裝起來framework往往需要把命令請求與處理請求的對象分開,command模式可以把調(diào)用操作的對象與操作的目標對象分開允許通過多種途
41、徑調(diào)用同一個請求?!埱蟮闹赜?Command模式(二),Applicability:Use the Command pattern when : parameterize objects by an action to perform,代替回調(diào)specify, queue, and execute requests at different timessupport undosupport logging changes s
42、o that they can be reapplied in case of a system crashstructure a system around high-level operations built on primitives operations —— transactions,Command模式(三),StructParticipantsClient, Command、ConcreteCommand
43、、Invoker、Receiver,Command模式(四),Collaborations,Command模式(五),EvaluationCommand decouples the object that invokes the operation from the one that knows how to perform it. Commands are first-class objects. They can be mani
44、pulated and extended like any other object. You can assemble commands into a composite command. An example is MacroCommand.It's easy to add new Commands, because you don't have to change existing classes. Impl
45、ementationHow intelligent should a command be?Supporting undo and redoAvoiding error accumulation in the undo processUsing C++ templates,Command模式(六),Related PatternsComposite模式可用來實現(xiàn)command組合為實現(xiàn)undo/redo,可以用其他行為模式來
46、管理狀態(tài),如memento模式。Command被放到history list之前,可以用prototype模式復(fù)制自身Examples,模式 13:Iterator(一),Aliases :CursorIntentProvide a way to access the elements of an aggregate object sequentially without exposing its underlying repre
47、sentation.MotivationAn aggregate object such as a list should give you a way to access its elements without exposing its internal structure.Separating the traversal mechanism from the List object lets us define iterat
48、ors for different traversal policies without enumerating them in the List interface.,Iterator模式(二),Applicability:Use the Iterator pattern when : to access an aggregate object's contents without exposing its internal
49、 representation.to support multiple traversals of aggregate objects.to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).,Iterator模式(三),StructP
50、articipantsIterator、ConcreteIterator、Aggregate、ConcreteAggregateCollaborations,Iterator模式(四),EvaluationIt supports variations in the traversal of an aggregateIterators simplify the Aggregate interfaceMore than one t
51、raversal can be pending on an aggregateImplementation實現(xiàn)可以非常靈活Who controls the iteration? external iterator versus internal iteratorWho defines the traversal algorithm? Aggregate本身定義算法 —— Cursor modeiterator定義算法 ——
52、 iterator如何訪問數(shù)據(jù)How robust is the iterator?,Iterator模式(五),Implementation(續(xù))Additional Iterator operations. 基本操作:First, Next, IsDone, and CurrentItemUsing polymorphic iterators —— iterator資源釋放Iterators may have privil
53、eged accessIterators for composites —— 適合于internal iterator或者cursor方式的iteratorNull iterators,Iterator模式(六),Related PatternsComposite:iterator常被用于composite模式的復(fù)合結(jié)構(gòu)Polymorphic iterators rely on factory methods to instan
54、tiate the appropriate Iterator subclass.ExamplesCOM enumerator:connectable object、…ADO/OLE DBC++ STL在STL中,iterator是連接algorithm和container的橋梁,模式 14:Observer(一),Aliases :Dependents, Publish-SubscribeIntentDefine a o
55、ne-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.Motivation把系統(tǒng)分成一些相互關(guān)聯(lián)的類或者對象,如何維護這些類的實例一致性?The key objects in this pattern are subj
56、ect and observer One-to-many relationshipA subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state.,Observer模式(二),Applicability:Use the Observer
57、pattern when : When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. When a change to one object requires changing
58、others, and you don't know how many objects need to be changed. When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these
59、objects tightly coupled.,Observer模式(三),StructParticipantsSubject、ConcreteSubject、Observer、ConcreteObserver,Observer模式(四),Collaborations,Observer模式(五),EvaluationAbstract coupling between Subject and ObserverSupp
60、ort for broadcast communicationUnexpected updatesImplementationMapping subjects to their observers. Observing more than one subjectWho triggers the update? Client or subject?Making sure Subject state is self-consis
61、tent before notificationsubject向observer傳遞變化信息中間插入ChangeManager,Observer模式(六),Related PatternsMediator:用Mediator模式封裝復(fù)雜的更新語義ExamplesCOM property pageCOM+ Event Model,MVC,模式 15:Strategy(一),Aliases :PolicyIntentDef
62、ine a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.Motivation有些算法對于某些類是必不可少的,但是不適合于硬編進類中??蛻艨赡苄枰惴ǖ亩喾N不同實現(xiàn),允許增加新的算法實現(xiàn)或
63、者改變現(xiàn)有的算法實現(xiàn)我們可以把這樣的算法封裝到單獨的類中,稱為strategy,Strategy模式(二),Applicability:Use the Strategy pattern when : many related classes differ only in their behavior. you need different variants of an algorithm. an algorithm uses d
64、ata that clients shouldn't know about. a class defines many behaviors, and these appear as multiple conditional statements in its operations.,Strategy模式(三),StructParticipantsStrategy、ConcreteStrategy、Context
65、CollaborationsStrategy and Context interact to implement the chosen algorithmA context forwards requests from its clients to its strategy,Strategy模式(四),EvaluationFamilies of related algorithmsAn alternative to subcla
66、ssingStrategies eliminate conditional statementsClients must be aware of different StrategiesCommunication overhead between Strategy and ContextIncreased number of objectsImplementationDefining the Strategy and Con
67、text interfacesStrategies as template parametersMaking Strategy objects optional,Strategy模式(五),Related Patternsflyweight:考慮用flyweight模式來實現(xiàn)strategy對象ExamplesATL中COM對象的線程模型支持,模式 16:Visitor(一),IntentRepresent an opera
68、tion to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.Motivation為了把一個操作作用于一個對象結(jié)構(gòu)中,一種做法是把這個操作分散到每一個節(jié)點上。導(dǎo)致系
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 眾賞文庫僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 軟件設(shè)計文檔模板
- 軟件設(shè)計文檔模板
- “選課系統(tǒng)”軟件設(shè)計文檔
- 軟件設(shè)計模式課程設(shè)計
- 軟件設(shè)計文檔國家標準gb8567
- 軟件設(shè)計模式與體系結(jié)構(gòu)
- 軟件設(shè)計模式大作業(yè)樣例
- 基于XML文檔的監(jiān)控組態(tài)軟件設(shè)計.pdf
- 軟件體系結(jié)構(gòu)及軟件設(shè)計模式概述
- 軟件設(shè)計模式研究與應(yīng)用.pdf
- 《軟件設(shè)計模式》在線平時作業(yè)3
- 軟件設(shè)計模式研究及應(yīng)用.pdf
- 《軟件設(shè)計模式》在線平時作業(yè)1
- “考試題庫系統(tǒng)”軟件設(shè)計文檔
- 軟件設(shè)計模式庫研究與實現(xiàn).pdf
- 軟件設(shè)計模式的研究及應(yīng)用.pdf
- 通信軟件設(shè)計模式的研究與應(yīng)用.pdf
- 《軟件設(shè)計模式》在線平時作業(yè)1-00001
- 基于UML的軟件設(shè)計模式建模研究.pdf
- 開放式運動控制器的軟件設(shè)計.pdf
評論
0/150
提交評論