軟件相關設計模式(一)_第1頁
軟件相關設計模式(一)_第2頁
軟件相關設計模式(一)_第3頁
軟件相關設計模式(一)_第4頁
軟件相關設計模式(一)_第5頁
已閱讀5頁,還剩58頁未讀, 繼續免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、軟件相關設計模式(一)Why Patterns?內容從一個例子看模式關于模式的研究情況介紹一些重要的模式(部分)第三次作業一個設計例子VC/Samples/MFC/OLE/DrawCliDrawCli的基礎MFC提供的基礎Doc/View結構Doc提供了強大的數據管理功能View提供了強大的顯示功能splitwnd功能CWinApp/CMainFrame提供了一套命令處理流程對OLE的封裝Active ContainerOLE ClipboardProperty Page數據結構管理功能CObject/CObList我們的設計焦點用C+對象來表示每一個圖元定義圖元的公共接口如何處理用戶的操作鼠

2、標的動作圖元對象的創建和管理圖元基類class CDrawObj : public CObject/ AttributesCDrawDoc* m_pDocument;/ ownervirtual int GetHandleCount();virtual CPoint GetHandle(int nHandle);virtual HCURSOR GetHandleCursor(int nHandle);virtual void SetLineColor(COLORREF color);virtual void SetFillColor(COLORREF color);/ Operationsvi

3、rtual void Draw(CDC* pDC);virtual void DrawTracker(CDC* pDC, TrackerState state);virtual void MoveTo(const CRect& positon, CDrawView* pView = NULL);virtual int HitTest(CPoint point, CDrawView* pView, BOOL bSelected);virtual BOOL Intersects(const CRect& rect);virtual void MoveHandleTo(int nHa

4、ndle, CPoint point, CDrawView* pView = NULL);virtual void OnOpen(CDrawView* pView);virtual void OnEditProperties();virtual CDrawObj* Clone(CDrawDoc* pDoc = NULL);virtual void Remove();virtual void Serialize(CArchive& ar);/ ;圖元層次結構 CDrawObj CDrawRect CDrawPoly CDrawOleObj CDrawObjCDrawRectCDrawPo

5、ly CDrawOleObj圖元的創建永久支持:CDocument:Serialize-CObList:Serialize-CObject:SerializeCDrawObj:CloneDrawTool:創建圖元對象交互操作鍵盤和菜單命令MFC內部機制鼠標操作在CDrawView的鼠標處理函數中處理工具箱:工具鏈,有一個當前活動工具轉交給當前活動工具來處理工具箱和CDrawToolclass CDrawTool/ Constructorspublic:CDrawTool(DrawShape nDrawShape);/ Overridablesvirtual void OnLButtonDown

6、(CDrawView* pView, UINT nFlags, const CPoint& point);virtual void OnLButtonDblClk(CDrawView* pView, UINT nFlags, const CPoint& point);virtual void OnLButtonUp(CDrawView* pView, UINT nFlags, const CPoint& point);virtual void OnMouseMove(CDrawView* pView, UINT nFlags, const CPoint& poi

7、nt);virtual void OnEditProperties(CDrawView* pView);virtual void OnCancel();/ AttributesDrawShape m_drawShape;static CDrawTool* FindTool(DrawShape drawShape);static CPtrList c_tools;static DrawShape c_drawShape;/ ;DrawTool層次結構 CDrawTool CSelectTool CRectTool CPolyTool CDrawToolCSelectToolCRectToolCP

8、olyTool例子中的模式CDrawObj和CDrawTool合起來構成了Factory Method模式CDrawTool:Clone用到了原型創建模式每一個CDrawTool都是一個singletonAdapter模式:把OLE對象封裝成CDrawObj* 可以增加Composite模式facade模式:通過CDrawDoc/View與MFC通信chain of responsibility:如鼠標處理工作* 用Command模式增加undo/redo功能patterns 定義: A physical arrangement of elements Repeating;with some

9、degree of correspondence in successive trials or observations 典范、范例,事物的標準樣式 In the book “Design Patterns”, the design patterns are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context Design patterns represent solutions to pr

10、oblems that arise when developing software within a particular context 幾個近義詞 idiom、technique、paradigmAbout patterns About patterns Documentation of expert software engineers behavior Documentation of specific reoccurring problems (and solutions) Abstraction of common design occurrences Properties of

11、 design patterns A pattern addresses a recurring design problem that arises in specific design situations, and presents a solution to it. Patterns document existing, well-proven design experience. Patterns provide a common vocabulary and understanding for design principles. Patterns are a means of d

12、ocumenting software architectures. Patterns support the construction of software with define properties. Patterns help you to manage software complexity. pattern與framework Patterns支持軟件結構和設計的重用 抓住了特定領域中問題的成功解決方案中的靜態、動態結構和相互之間的協作關系 patterns與開發語言無關,但是建立在一定的環境基礎上 例如:經典的MVC、Factory Method frameworks支持細節設

13、計和代碼的重用 framework是一組組件的綜合,這些組件相互協作,為一族相關應用提供了一個可重用的框架結構 例如:MMC、MS Script Engine 兩者結合起來, design patterns and frameworks有助于提高軟件的質量 比如:重用性,擴展性,性能,可維護性Design pattern與framework(續) a framework supplies the infrastructure and mechanisms that execute a policy for interaction between abstract components with

14、 open implementations. frameworks are often said to abide by the Hollywood Principle (Dont call us, well call you.) 比較: Design patterns are more abstract than frameworks Design patterns are smaller architectural elements than frameworks Design patterns are less specialized than frameworks framework與

15、class library(toolkit)Pattern的研究情況關于pattern研究的歷史A Pattern Language,Christopher Alexander,1977“Advanced C+:Programming Styles and Idioms”,James Coplien,1992“Design Patterns: Elements of Reusable Object-Oriented Software”,GOF,1995“Pattern-Oriented Software Architecture: A System of Patterns” (簡稱為“POSA

16、”) ,GoV,1996.Pattern is a hot topic在amazon上查找包含patterns的書(2002.12.12)Pattern的研究現狀pattern與Javapattern與CORBApattern與系統結構pattern與generic programming結合其他(例如UML等)POSA中的模式分類 Architectural Patterns 表達了軟件系統的基本結構組織形式或者結構方案 它包含一組預定義的子系統,規定了這些子系統的責任,同時還提供了用于組織和管理這些子系統的規則和向導 Design Patterns 為軟件系統的子系統、組件或者組件之間的關

17、系提供一個精煉之后的解決方案 它描述了在特定環境下,用于解決通用軟件設計問題的組件以及這些組件相互通信時的可重現結構 Idioms 是一個與編程語言相關的低級模式 它描述了如何實現組件的某些功能,或者利用編程語言的特性來實現組件內部要素之間的通信功能POSA: Architectural Patterns(1) Architectural Patterns are very high-level structural patterns. Also called “Conceptual Patterns ” From Mud to Structure: Organize components.

18、Layers: Organize components into layers where layer is services are only used by layer i+1. Pipes and Filters: Divide the task into several sequential processing steps - the output of task i is the input of task i+1. Blackboard: Several independent programs work cooperatively on a common data struct

19、ure. Distributed Systems :Handle distributed computation. Broker: Introduce a broker component to to achieve better decoupling of clients and servers - brokers accept requests from clients and forward the requests to servers, then return the results back to the clients. POSA: Architectural Patterns(

20、2) Interactive Systems: Keep a programs functional core independent of the user interface Model - View - Controller: Divides the application into processing, output, and input. View and controller parts are usually observers of the model via the observer pattern Presentation - Abstract - Control: Di

21、vides the application up to heirarchies or MVC-like components. Each component is dependent upon and provides functionality for the a higher-level component. There is only one top-level component Adaptable Systems : Design for change Microkernel Encapsulate the fundamental services of the applicatio

22、n Reflection Divide the application into a meta-level and a base level to make the application self-aware. The meta level encapsulates knowledge of the system; the base level encapsulates knowledge about the problem domainPOSA: Design Patterns(1) Structure Decomposition: Decompose subsystems and com

23、plex components into cooperating parts. Whole - Part: Define a component that encapsulates smaller objects. Prevent clients from directly accessing the contained objects, but provide a interface for the aggregate. Organization of Work : Components collaborate to solve complex problems. Master - Slav

24、e The master divides a task among identical (but independent) slaves, the combines the slaves partial results to arrive a solution. Access Control : Guard and control access to services and components. Proxy: Clients communicate with a representative (proxy) rather than the target object itself. The

25、 proxy can perform pre- and post-processing to provide validation checking, access control, remote object access, extra computation, etc. See also Gamma et als proxy patternPOSA: Design Patterns(2) Management: Handle homogenous collections of objects, services and components in their entirety. Comma

26、nd Processor: Extends Gamma et als command pattern by adding an explicit command processor View Handler: Separate the the management of views from the code required to present or control specific views. Similar to Gamma et als Abstract Factory and Mediator. Communication :Organize communication betw

27、een components. Forward - Receiver: Contain all system-specific communication functionality in separate components so distributed peers can communicate without loosing portability Client - Dispatcher - Server: A dispatcher acts as an intermediate layer between clients and servers. The dispatcher pro

28、vides the communication channel and a name service to hide physical locations. Publisher - Subscriber: Same as Gamma et als Observer pattern. IdiomsAlso called “Programming Patterns”Idioms are low-level patterns specific to a programming language. Counted Pointer: Simplifies memory management of sha

29、red objects providing reference counting. 其他Virtual constructorsmart pointerhandle/body關于“Design Pattern”對已有模式的整理、分類一套描述模式的詞匯,可用于交流和文檔化為軟件設計總結了寶貴的經驗,這些設計經驗可以被重用,但不是簡單的代碼重用分類:Creational PatternsStructural PatternsBehavioral Patterns在軟件設計模式領域,起到先驅的作用重提:指導模式設計的三個概念重用(reuse):是目標兩種重要的重用手段Inheritance &

30、; composition接口與實現分離接口保持不變,分離帶來靈活性多態性(polymorphism)Decouple降低復雜性如何描述一個模式 關鍵要素 Design pattern name,Aliases or Also Known As Problem,Intent or Goal Forces,Constraints,Motivation Context, Applicability Solution Structure Participants Collaboration Implementation Evaluation,Resulting Context,Consequence

31、s Related Patterns Examples,Known usescreational patternsAbstract Factory(kit)BuilderFactory Method(virtual constructor)PrototypeSingleton* Finder模式 1:Factory Method (一)Aliases:virtual constructorIntentDefine an interface for creating an object, but let subclasses decide which class to instantiate.

32、Factory Method lets a class defer instantiation to subclasses.MotivationFrameworks use abstract classes to define and maintain relationships between objects. A framework is often responsible for creating these objects as well.Factory Method模式(二)Applicability:Use the Factory Method pattern whena clas

33、s cant anticipate the class of objects it must create. a class wants its subclasses to specify the objects it creates. classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. 插:virtual constructorintent:在一個

34、類層次中,客戶在runtime要創建一個對象,對象的子類型未確定,根據客戶的需要和環境情況,確定對象的類型problem:只知道對象的一般類型,不知道確切類型(需要從環境中獲取類型信息)Forces :隱藏對象的類型層次,只發布基接口如何確定最合適的派生類客戶必須有辦法使用派生類的服務插:virtual constructor(續)solution:使用Envelope/Letter或者Handle/Body pattern由envelope或者handle根據環境信息選擇適當的派生類型例子:1 根據stream動態創建對象2 COM對象Factory Method模式(三)struct Pa

35、rticipants Product、ConcreteProduct、Creator、ConcreteCreator CollaborationsFactory Method模式(四)Evaluation多態性:客戶代碼可以做到與特定應用無關,適用于任何實體類缺點:需要Creator和相應的子類作為factory method的載體,如果應用模型確實需要creator和子類存在,則很好;否則的話,需要增加一個類層次優點:(1) Provides hooks for subclasses。基類為factory method提供缺省實現,子類可以重寫新的實現,也可以繼承父類的實現。體現了:加一層間

36、接性,增加了靈活性(2) Connects parallel class hierarchiesFactory Method模式(五)Connects parallel class hierarchiesFactory Method模式(六)Implementation(1) 父類是否提供缺省的實現(2) factory method的參數(3) Language-specific variants and issuesSmallTalk,使用類型C+,使用lazy initialization技術(4) Using templates to avoid subclassingFactory

37、Method模式(七) Related Patterns Abstract factory Prototype Examples模式 2 :Abstract Factory(一)Aliases:KitIntentProvide an interface for creating families of related or dependent objects without specifying their concrete classes.Motivation為了解決一族相關或者相依對象的創建工作,專門定義一個用于創建這些對象的接口(基類)??蛻糁恍枧c這個基接口打交道,不必考慮實體類的類型。

38、Abstract Factory(二)Applicability,Use the Abstract Factory pattern whena system should be independent of how its products are created, composed, and represented. a system should be configured with one of multiple families of products. a family of related product objects is designed to be used togethe

39、r, and you need to enforce this constraint. you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations. Abstract Factory(三)StructParticipants: Client、AbstractFactory、ConcreteFactory、AbstractProduct、ConcreteProductCollaborations Abstract F

40、actory(四)Evaluation與factory method的關系多個factory method合在一起factory method一定是virtual的Abstract Factory(五)Evaluation(續)優點:factory把product的類型封裝起來,分離了具體的類易于變換product族保證不同族之間的product相互不會碰撞,即保證products的一致性缺點:factory對象的方法數目對應product數目,增加新的product種類比較困難,要影響到factory的基類,進而影響到所有的子類Abstract Factory(六)Implementatio

41、nFactories as singletons, 每個product族往往只需要一個factory對象就可以了Creating the products, 對于product族比較多的情況,可以使用prototype模式來實現這些factories,而不必對于每一個具有細微差別的product族都使用一個concrete factory classDefining extensible factories,針對Evaluation中提到的缺點,通過參數化技術提高factory的適應能力和擴展性 問題在于,返回給客戶什么樣的類型?Abstract Factory(七)Related Patte

42、rnsFactory Method、Prototype 、Singleton ExamplesWidgetFactory插:COM中的class factory 兼有兩種模式:factory method和abstract factory IClassFactory是abstract factory的接口 CreateInstance是factory method 對于每一個coclass,class object就是Concrete Factory, 每一個產品的抽象接口為IUnknown,COM對象是真正的concrete product IPSFactoryBuffer也是abstrac

43、t factory的接口 通過factory method創建對象 比客戶直接創建對象,要靈活 ConcreteFactory也是一個concrete product,所以可以重用底層的許多機制,如套間機制、跨進程機制等模式三:Builder (一) Intent Separate the construction of a complex object from its representation so that the same construction process can create different representations Motivation 在復雜對象的構造過程中

44、,允許同樣的構造過程能夠加入新的被構造元素 “結構化構造過程” Applicability, Use the Builder pattern when the algorithm for creating a complex object should be independent of the parts that make up the object and how theyre assembled. the construction process must allow different representations for the object thats constructed.

45、Builder (二)StructureParticipantsDirector、 Builder、ConcreteBuilder、 ProductBuilder (三)CollaborationsBuilder (四)EvaluationIt lets you vary a products internal representationIt isolates code for construction and representationIt gives you finer control over the construction processImplementationBuilder

46、 interface(Assembly and construction)Why no abstract class for products? Empty methods as default in Builder. Related patternsAbstract Factory 區別:(1) builder重在構造過程,最后一步返回結果; (2) builder構造許多復雜對象Builder (五)Examplesreaders、parsers、convertersthe persistence of OLE documents模式四:Prototype(一) IntentSpecify

47、 the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. Motivation 以一個已有的對象作為原型,通過它來創建新的對象。在增加新的對象的時候,新對象的細節創建工作由自己來負責,從而使新對象的創建過程與框架隔離開來 Applicability 當產品的創建過程要獨立于系統時 當產品的類型是在runtime時被指定的情況下 避免創建一個與product層次平行的factory層次時Prototype(二)StructureP

48、articipantsPrototype、ConcretePrototype、ClientCollaborationsPrototype(三) Evaluation Adding and removing products at run-time Specifying new objects by varying values,降低系統中類的數目 Configuring an application with classes dynamically 要求:每一個product類都必須實現Clone操作 對于C+語言特別有意義:C+的class不是first-class objects Impl

49、ementation Using a prototype manager Implementing the Clone operationshallow copy versus deep copySave & Load Initializing clones 兩階段構造Prototype(四) Related patterns Prototype與Abstract Factory往往是相互競爭的 factory method Examples DrawCli,music editor模式五:Singleton(一)IntentEnsure a class only has one instance, and provide a global point of access to it.MotivationIts important for some classes to have exactly one instance.Instance-controlled classApplicability, Use the Singleton pattern whenthere must be exactly one instance of a class, and it mu

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論