软件设计模式(一)-开放文档-FreeandOpen.ppt

上传人:ga****84 文档编号:494582 上传时间:2018-10-15 格式:PPT 页数:77 大小:616.50KB
下载 相关 举报
软件设计模式(一)-开放文档-FreeandOpen.ppt_第1页
第1页 / 共77页
软件设计模式(一)-开放文档-FreeandOpen.ppt_第2页
第2页 / 共77页
软件设计模式(一)-开放文档-FreeandOpen.ppt_第3页
第3页 / 共77页
软件设计模式(一)-开放文档-FreeandOpen.ppt_第4页
第4页 / 共77页
软件设计模式(一)-开放文档-FreeandOpen.ppt_第5页
第5页 / 共77页
点击查看更多>>
资源描述

1、软件设计模式(二),潘爱民http:/ PatternsBehavioral Patterns,复习:pattern定义,定义:特定环境中问题的成功解决方案中的静态、动态结构,以及结构元素相互之间的协作关系Design patterns represent solutions to problems that arise when developing software within a particular context关于pattern的研究状况研究历史现状pattern与框架pattern的分类粒度,复习:如何描述一个模式,关键要素Design pattern name,Aliases

2、 or Also Known AsProblem,Intent or GoalForces,Constraints,MotivationContext, ApplicabilitySolution StructureParticipantsCollaborationImplementationEvaluation,Resulting Context,ConsequencesRelated Patterns Examples,Known uses,复习:creational patters,Factory Method本质:用一个virtual method完成创建过程Abstract Fact

3、ory一个product族的factory method构成了一个factory接口Prototype通过product原型来构造product,Clone+prototype managerBuilder通过一个构造算法和builder接口把构造过程与客户隔离开Singleton单实例类型,如何构造这单个实例?如何访问这单个实例?Finder把对象的获取过程与客户隔离开,creational patterns小结,了解每一种模式的实质具体实现的时候可能会有变化情况,或者扩展,或者退化factory method是基础,abstract factory是它的扩展factory method、a

4、bstract factory、prototype都涉及到类层次结构中对象的创建过程,有所取舍prototype需要prototype managerfactory method需要依附一个creator类abstract factory需要一个平行的类层次根据应用的其他需求,以及语言提供的便利来决定使用哪种模式,creational patterns小结(续),builder往往适合于特定的结构需要,它所针对的product比较复杂singleton有比较强烈的物理意义,可以用在许多细微的地方,不一定与类层次关联finder模式需要有一定范围内的对象管理功能这些patterns都很常见,有时

5、需要结合两种或者多种模式完成系统中对象的构造过程,Structural Patterns,Adapter Bridge Composite * Decorator Facade Flyweight * Proxy,模式 7: Adapter (一),Aliases:WrapperIntentConvert the interface of a class into another interface clients expect. Adapter lets classes work together that couldnt otherwise because of incompatible

6、interfaces.MotivationSometimes a toolkit class thats designed for reuse isnt reusable only because its interface doesnt match 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 ma

7、tch the one you need.you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that dont necessarily have compatible interfaces.(object adapter only) you need to use several existing subclasses, but its impractical to adapt their interface by subclass

8、ing every one. An object adapter can adapt the interface of its parent class.,Adapter模式(三),Structclassadapter objectadapter,Adapter模式(三),ParticipantsClient、Target、Adaptee、AdapterCollaborationsclass adapter delegationobject adapter container,Adapter模式(四),Evaluation本质上是两种重用模型class adapter:无法adapt adap

9、tee的子类,但是可以重载adaptee的行为object adapter可以adapt adaptee的所有子类How much adapting does Adapter do? Pluggable adaptersUsing two-way adapters to provide transparency针对class adapter,用多重继承来实现,Adapter模式(五),Implementation使用C+继承机制实现class adapter使用内嵌对象技术实现object adapterPluggable adapters,三种实现方案使用抽象方法定义使用代理对象参数化技术这

10、三种方法的实质:如何在一个类中定义抽象操作,供客户插入? hook 技术,Adapter模式(六),Related PatternsBridgeDecoratorProxyExamplesDrawCli:COleDrawObjC+ STLCOM中的site,模式 8:Bridge(一),Aliases:Handle/BodyIntentDecouple an abstraction from its implementation so that the two can vary independentlyMotivation要做到“抽象(接口)与实现分离”,最常用的办法是定义一个抽象类,然后在

11、子类中提供实现。也就是说,用继承机制达到“抽象(接口)与实现分离”但是这种方法不够灵活,继承机制把实现与抽象部分永久地绑定起来,要想独立地修改、扩展、重用抽象(接口)与实现都非常困难。,Bridge模式(二),Applicability:Use the Bridge pattern when编译时刻无法确定抽象(接口)与实现之间的关系抽象部分与实现部分都可以通过子类化而扩展对一个实现的修改不影响客户(无须重新编译)在C+中,对客户完全隐瞒实现细节因为扩展的原因,需要把一个类分成两部分,(以便灵活组合)在多个对象之间共享数据,但客户不需要知道,Bridge模式(三),StructParticip

12、antsClient, Abstraction, RefinedAbstraction, Implementor, ConcreteImplementorCollaborations,Bridge模式(四),Evaluation抽象部分与实现部分的分离,可以在运行时刻连接起来二进制兼容性提高可扩充性:抽象与实现两部分可以单独扩充对客户隐藏实现细节,Bridge模式(五),ImplementationOnly one ImplementorCreating the right Implementor object如何创建?根据客户环境,或者通过factorySharing implementor

13、s资源管理:引用计数技术Using multiple inheritance,Bridge模式(六),Related PatternsAbstract Factory可以用来创建和配置Bridge模式与Adapter模式的区别Exampleshandle:文件handle、窗口handle,插:Handle/Body,class StringRep friend class String;StringRep(const char *s);StringRep();int count; char *rep;class String public:String();String(const Stri

14、ng ,Counted Handle/Body,模式 9:Composite(一),IntentCompose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.Motivation一些部件对象经过组合构成的复合部件对象仍然具有单个部件对象的接口,这样的复合部件对象被称为“容器(container)”复合部件与单个部件具有同样的接口,所有接口包

15、含两部分:单个部件的功能、管理子部件的功能递归组合,Composite模式(二),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 objects. Clients will treat all objects in the composite s

16、tructure uniformly.,Composite模式(三),StructParticipantsClient, Component, Leaf, CompositeCollaborations,典型的composite对象结构,Composite模式(四),Evaluationdefines class hierarchies consisting of primitive objects and composite objects。定义了包含leaf对象和composite对象的类层次接口。递归结构makes the client simple。客户一致地处理复合对象和单个对象ma

17、kes it easier to add new kinds of components。易于增加新类型的组件can make your design overly general。使得系统过于一般化,无法限制类型的组合,可以在运行时刻通过类型检查加以弥补,Composite模式(五),ImplementationExplicit parent referencesSharing componentsMaximizing the Component interfaceDeclaring the child management operationsShould Component implem

18、ent a list of Components? Child orderingCaching to improve performanceWho should delete components? Whats the best data structure for storing components?,Composite模式(六),Related PatternsDecorator、Flyweight、Iterator、VisitorExamples广泛应用于OO领域MFC中的CWnd组件层次:ActiveX Container,模式 10:Facade(一),IntentProvide

19、a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.Motivation使系统的各子系统之间的关联最小,引入一个facade对象,为子系统提供一个简单的、泛化的设施,Facade模式(二),Applicability:Use the Facade pattern when为一个复杂的子系统提供一个简单接口时。子系统往往会非常复杂,但是其接口应该尽可能地简单,特别是对于一般用

20、户而言客户与抽象类的实现部分之间必然存在一定的依赖性,facade可以降低这种依赖性在多个子系统的结构中,使用facade模式定义子系统的入口点,有助于降低各子系统之间的依赖性,Facade模式(三),StructParticipantsfacade, subsystem classesCollaborations,Facade模式(四),Evaluation简化子系统的接口,方便客户使用子系统化“紧耦合”为“松耦合” 实现组件软件的关键技术facade模式并不限制客户直接访问子系统的内部类和对象Implementation以抽象类的形式定义facade,进一步decouple,从而完全隔离子

21、系统的细节Public versus private subsystem classes,Facade模式(五),Related Patternsfacade对象的创建:singleton、abstract factoryExamples,模式 11:FlyWeight(一),IntentUse sharing to support large numbers of fine-grained objects efficiently.Motivation当对象的粒度太小的时候,大量对象将会产生巨大的资源消耗,因此考虑用共享对象(flyweight)来实现逻辑上的大量对象。Flyweight对象可

22、用于不同的context中,本身固有的状态不随context发生变化,而其他的状态随context而变化,FlyWeight模式(二),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 be made extrinsic. Man

23、y groups of objects may be replaced by relatively few shared objects once extrinsic state is removed. The application doesnt depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.,FlyWeight模式(三),Struct,FlyWeight模式(四),Struc

24、t(续)Participantsclient, flyweight, concreteFlyweight, FlyweightFactory,UnsharedConcreteFlyweightCollaborations,FlyWeight模式(五),Evaluation把对象的状态分开:intrinsic and extrinsic 节约存储空间:内部状态的共享节约了大量空间,外部状态可通过计算获得从而进一步节约空间flyweight与composite结合。Flyweight为leaf节点,并且父节点只能作为外部状态ImplementationRemoving extrinsic stat

25、e,尽可能做到实时计算(通过一个小的数据结构)Managing shared objects,客户不能直接实例化flyweight,必须通过管理器,例如FlyweightFactory。flyweight的生命周期管理,引用计数和回收,FlyWeight模式(六),Related Patterns与Composite模式组合可以用flyweight实现State和Strategy模式中的对象ExamplesExcel中cell的管理IOleItemContainer接口允许客户发现每一个cell对象用flyweight实现cell对象 tearoff技术对状态的有效管理是对象技术的一个进步“D

26、esign Patterns”中提到的文档编辑器的例子,Structural Patterns :Decorator,Structural Patterns :Proxy,Structural patterns小结,Adapter 、bridge、facadeadapter用于两个不兼容接口之间的转接bridge用于将一个抽象与多个可能的实现连接起来facade用于为复杂的子系统定义一个新的简单易用的接口composite、decorator和proxycomposite用于构造对象组合结构decorator用于为对象增加新的职责proxy为目标对象提供一个替代者flyweight针对细粒度对

27、象的一种全局控制手段,Behavioral Patterns,Chain of Responsibility *Command Interpreter *Iterator Mediator *Memento *Observer State *Strategy Template Method *Visitor,模式 12:Command(一),AliasesAction, Transactionfunctor (function object)IntentEncapsulate a request as an object, thereby letting you parameterize cl

28、ients with different requests, queue or log requests, and support undoable operations.Motivation把请求信息和请求执行过程封装起来framework往往需要把命令请求与处理请求的对象分开,command模式可以把调用操作的对象与操作的目标对象分开允许通过多种途径调用同一个请求。请求的重用,Command模式(二),Applicability:Use the Command pattern when : parameterize objects by an action to perform,代替回调s

29、pecify, queue, and execute requests at different timessupport undosupport logging changes so 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、

30、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 manipulated and extended like any other object. You can assemble commands into a compos

31、ite command. An example is MacroCommand.Its easy to add new Commands, because you dont have to change existing classes. ImplementationHow intelligent should a command be?Supporting undo and redoAvoiding error accumulation in the undo processUsing C+ templates,Command模式(六),Related PatternsComposite模式

32、可用来实现command组合为实现undo/redo,可以用其他行为模式来管理状态,如memento模式。Command被放到history list之前,可以用prototype模式复制自身Examples,模式 13:Iterator(一),Aliases :CursorIntentProvide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.MotivationAn aggregate object such a

33、s 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 iterators for different traversal policies without enumerating them in the List interface.,Iterator模式(二),Applicability:Use the Iterator

34、 pattern when : to access an aggregate objects contents without exposing its internal 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模式(三),StructParti

35、cipantsIterator、ConcreteIterator、Aggregate、ConcreteAggregateCollaborations,Iterator模式(四),EvaluationIt supports variations in the traversal of an aggregateIterators simplify the Aggregate interfaceMore than one traversal can be pending on an aggregateImplementation实现可以非常灵活Who controls the iteration?

36、external iterator versus internal iteratorWho defines the traversal algorithm? Aggregate本身定义算法 Cursor modeiterator定义算法 iterator如何访问数据How robust is the iterator?,Iterator模式(五),Implementation(续)Additional Iterator operations. 基本操作:First, Next, IsDone, and CurrentItemUsing polymorphic iterators iterato

37、r资源释放Iterators may have privileged accessIterators for composites 适合于internal iterator或者cursor方式的iteratorNull iterators,Iterator模式(六),Related PatternsComposite:iterator常被用于composite模式的复合结构Polymorphic iterators rely on factory methods to instantiate the appropriate Iterator subclass.ExamplesCOM enume

38、rator:connectable object、ADO/OLE DBC+ STL在STL中,iterator是连接algorithm和container的桥梁,模式 14:Observer(一),Aliases :Dependents, Publish-SubscribeIntentDefine a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.Motivation把系

39、统分成一些相互关联的类或者对象,如何维护这些类的实例一致性?The key objects in this pattern are subject 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 pattern when

40、: 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 others, and you dont know how many objects need to be changed. When an object should be able to

41、 notify other objects without making assumptions about who these objects are. In other words, you dont want these objects tightly coupled.,Observer模式(三),StructParticipantsSubject、ConcreteSubject、Observer、ConcreteObserver,Observer模式(四),Collaborations,Observer模式(五),EvaluationAbstract coupling between

42、Subject and ObserverSupport 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-consistent before notificationsubject向observer传递变化信息中间插入ChangeManage

43、r,Observer模式(六),Related PatternsMediator:用Mediator模式封装复杂的更新语义ExamplesCOM property pageCOM+ Event Model,MVC,模式 15:Strategy(一),Aliases :PolicyIntentDefine a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use i

44、t.Motivation有些算法对于某些类是必不可少的,但是不适合于硬编进类中。客户可能需要算法的多种不同实现,允许增加新的算法实现或者改变现有的算法实现我们可以把这样的算法封装到单独的类中,称为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 data that clients

45、shouldnt know about. a class defines many behaviors, and these appear as multiple conditional statements in its operations.,Strategy模式(三),StructParticipantsStrategy、ConcreteStrategy、ContextCollaborationsStrategy and Context interact to implement the chosen algorithmA context forwards requests from i

46、ts clients to its strategy,Strategy模式(四),EvaluationFamilies of related algorithmsAn alternative to subclassingStrategies eliminate conditional statementsClients must be aware of different StrategiesCommunication overhead between Strategy and ContextIncreased number of objectsImplementationDefining t

47、he Strategy and Context interfacesStrategies as template parametersMaking Strategy objects optional,Strategy模式(五),Related Patternsflyweight:考虑用flyweight模式来实现strategy对象ExamplesATL中COM对象的线程模型支持,模式 16:Visitor(一),IntentRepresent an operation to be performed on the elements of an object structure. Visito

48、r lets you define a new operation without changing the classes of the elements on which it operates.Motivation为了把一个操作作用于一个对象结构中,一种做法是把这个操作分散到每一个节点上。导致系统难以理解、维护和修改把这样的操作包装到一个独立的对象(visitor)中。然后在遍历过程中把此对象传递给被访问的元素。,不用visitor的compiler例子,使用visitor的compiler例子,Visitor模式(二),Applicability:Use the Visitor pattern when一个对象结构包含许多对象类,我们想执行一些依赖于具体类的操作要对一个对象结构中的对象进行很多不同的并且不相关的操作,又不想改变这些对象类定义对象结构的类很少改变,但是经常要在此结构上定义新的操作。改变对象结构类,需要重定义所有visitor的接口,

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 学术论文资料库 > 毕业论文

Copyright © 2018-2021 Wenke99.com All rights reserved

工信部备案号浙ICP备20026746号-2  

公安局备案号:浙公网安备33038302330469号

本站为C2C交文档易平台,即用户上传的文档直接卖给下载用户,本站只是网络服务中间平台,所有原创文档下载所得归上传人所有,若您发现上传作品侵犯了您的权利,请立刻联系网站客服并提供证据,平台将在3个工作日内予以改正。