已阅读5页,还剩72页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
软件设计模式 二 潘爱民 内容 复习续 介绍一些重要的模式StructuralPatternsBehavioralPatterns 复习 pattern定义 定义 特定环境中问题的成功解决方案中的静态 动态结构 以及结构元素相互之间的协作关系Designpatternsrepresentsolutionstoproblemsthatarisewhendevelopingsoftwarewithinaparticularcontext关于pattern的研究状况研究历史现状pattern与框架pattern的分类粒度 复习 如何描述一个模式 关键要素Designpatternname AliasesorAlsoKnownAsProblem IntentorGoalForces Constraints MotivationContext ApplicabilitySolutionStructureParticipantsCollaborationImplementationEvaluation ResultingContext ConsequencesRelatedPatternsExamples Knownuses 复习 creationalpatters FactoryMethod本质 用一个virtualmethod完成创建过程AbstractFactory一个product族的factorymethod构成了一个factory接口Prototype通过product原型来构造product Clone prototypemanagerBuilder通过一个构造算法和builder接口把构造过程与客户隔离开Singleton单实例类型 如何构造这单个实例 如何访问这单个实例 Finder把对象的获取过程与客户隔离开 creationalpatterns小结 了解每一种模式的实质具体实现的时候可能会有变化情况 或者扩展 或者退化factorymethod是基础 abstractfactory是它的扩展factorymethod abstractfactory prototype都涉及到类层次结构中对象的创建过程 有所取舍prototype需要prototypemanagerfactorymethod需要依附一个creator类abstractfactory需要一个平行的类层次根据应用的其他需求 以及语言提供的便利来决定使用哪种模式 creationalpatterns小结 续 builder往往适合于特定的结构需要 它所针对的product比较复杂singleton有比较强烈的物理意义 可以用在许多细微的地方 不一定与类层次关联finder模式需要有一定范围内的对象管理功能这些patterns都很常见 有时需要结合两种或者多种模式完成系统中对象的构造过程 StructuralPatterns AdapterBridgeComposite DecoratorFacadeFlyweight Proxy 模式7 Adapter 一 Aliases WrapperIntentConverttheinterfaceofaclassintoanotherinterfaceclientsexpect Adapterletsclassesworktogetherthatcouldn totherwisebecauseofincompatibleinterfaces MotivationSometimesatoolkitclassthat sdesignedforreuseisn treusableonlybecauseitsinterfacedoesn tmatchthedomain specificinterfaceanapplicationrequires Adapter模式 二 Applicability UsetheAdapterpatternwhenyouwanttouseanexistingclass anditsinterfacedoesnotmatchtheoneyouneed youwanttocreateareusableclassthatcooperateswithunrelatedorunforeseenclasses thatis classesthatdon tnecessarilyhavecompatibleinterfaces objectadapteronly youneedtouseseveralexistingsubclasses butit simpracticaltoadapttheirinterfacebysubclassingeveryone Anobjectadaptercanadapttheinterfaceofitsparentclass Adapter模式 三 Structclassadapterobjectadapter Adapter模式 三 ParticipantsClient Target Adaptee AdapterCollaborationsclassadapter delegationobjectadapter container Adapter模式 四 Evaluation本质上是两种重用模型classadapter 无法adaptadaptee的子类 但是可以重载adaptee的行为objectadapter可以adaptadaptee的所有子类HowmuchadaptingdoesAdapterdo PluggableadaptersUsingtwo wayadapterstoprovidetransparency针对classadapter 用多重继承来实现 Adapter模式 五 Implementation使用C 继承机制实现classadapter使用内嵌对象技术实现objectadapterPluggableadapters 三种实现方案使用抽象方法定义使用代理对象参数化技术这三种方法的实质 如何在一个类中定义抽象操作 供客户插入 hook技术 Adapter模式 六 RelatedPatternsBridgeDecoratorProxyExamplesDrawCli COleDrawObjC STLCOM中的site 模式8 Bridge 一 Aliases Handle BodyIntentDecoupleanabstractionfromitsimplementationsothatthetwocanvaryindependentlyMotivation要做到 抽象 接口 与实现分离 最常用的办法是定义一个抽象类 然后在子类中提供实现 也就是说 用继承机制达到 抽象 接口 与实现分离 但是这种方法不够灵活 继承机制把实现与抽象部分永久地绑定起来 要想独立地修改 扩展 重用抽象 接口 与实现都非常困难 Bridge模式 二 Applicability UsetheBridgepatternwhen编译时刻无法确定抽象 接口 与实现之间的关系抽象部分与实现部分都可以通过子类化而扩展对一个实现的修改不影响客户 无须重新编译 在C 中 对客户完全隐瞒实现细节因为扩展的原因 需要把一个类分成两部分 以便灵活组合 在多个对象之间共享数据 但客户不需要知道 Bridge模式 三 StructParticipantsClient Abstraction RefinedAbstraction Implementor ConcreteImplementorCollaborations Bridge模式 四 Evaluation抽象部分与实现部分的分离 可以在运行时刻连接起来二进制兼容性提高可扩充性 抽象与实现两部分可以单独扩充对客户隐藏实现细节 Bridge模式 五 ImplementationOnlyoneImplementorCreatingtherightImplementorobject如何创建 根据客户环境 或者通过factorySharingimplementors资源管理 引用计数技术Usingmultipleinheritance Bridge模式 六 RelatedPatternsAbstractFactory可以用来创建和配置Bridge模式与Adapter模式的区别Exampleshandle 文件handle 窗口handle 插 Handle Body classStringRep friendclassString StringRep constchar s StringRep intcount char rep classString public String String constString CountedHandle Body 模式9 Composite 一 IntentComposeobjectsintotreestructurestorepresentpart wholehierarchies Compositeletsclientstreatindividualobjectsandcompositionsofobjectsuniformly Motivation一些部件对象经过组合构成的复合部件对象仍然具有单个部件对象的接口 这样的复合部件对象被称为 容器 container 复合部件与单个部件具有同样的接口 所有接口包含两部分 单个部件的功能 管理子部件的功能递归组合 Composite模式 二 Applicability UsetheCompositepatternwhenyouwanttorepresentpart wholehierarchiesofobjects youwantclientstobeabletoignorethedifferencebetweencompositionsofobjectsandindividualobjects Clientswilltreatallobjectsinthecompositestructureuniformly Composite模式 三 StructParticipantsClient Component Leaf CompositeCollaborations 典型的composite对象结构 Composite模式 四 Evaluationdefinesclasshierarchiesconsistingofprimitiveobjectsandcompositeobjects 定义了包含leaf对象和composite对象的类层次接口 递归结构makestheclientsimple 客户一致地处理复合对象和单个对象makesiteasiertoaddnewkindsofcomponents 易于增加新类型的组件canmakeyourdesignoverlygeneral 使得系统过于一般化 无法限制类型的组合 可以在运行时刻通过类型检查加以弥补 Composite模式 五 ImplementationExplicitparentreferencesSharingcomponentsMaximizingtheComponentinterfaceDeclaringthechildmanagementoperationsShouldComponentimplementalistofComponents ChildorderingCachingtoimproveperformanceWhoshoulddeletecomponents What sthebestdatastructureforstoringcomponents Composite模式 六 RelatedPatternsDecorator Flyweight Iterator VisitorExamples广泛应用于OO领域MFC中的CWnd组件层次 ActiveXContainer 模式10 Facade 一 IntentProvideaunifiedinterfacetoasetofinterfacesinasubsystem Facadedefinesahigher levelinterfacethatmakesthesubsystemeasiertouse Motivation使系统的各子系统之间的关联最小 引入一个facade对象 为子系统提供一个简单的 泛化的设施 Facade模式 二 Applicability UsetheFacadepatternwhen为一个复杂的子系统提供一个简单接口时 子系统往往会非常复杂 但是其接口应该尽可能地简单 特别是对于一般用户而言客户与抽象类的实现部分之间必然存在一定的依赖性 facade可以降低这种依赖性在多个子系统的结构中 使用facade模式定义子系统的入口点 有助于降低各子系统之间的依赖性 Facade模式 三 StructParticipantsfacade subsystemclassesCollaborations Facade模式 四 Evaluation简化子系统的接口 方便客户使用子系统化 紧耦合 为 松耦合 实现组件软件的关键技术facade模式并不限制客户直接访问子系统的内部类和对象Implementation以抽象类的形式定义facade 进一步decouple 从而完全隔离子系统的细节Publicversusprivatesubsystemclasses Facade模式 五 RelatedPatternsfacade对象的创建 singleton abstractfactoryExamples 模式11 FlyWeight 一 IntentUsesharingtosupportlargenumbersoffine grainedobjectsefficiently Motivation当对象的粒度太小的时候 大量对象将会产生巨大的资源消耗 因此考虑用共享对象 flyweight 来实现逻辑上的大量对象 Flyweight对象可用于不同的context中 本身固有的状态不随context发生变化 而其他的状态随context而变化 FlyWeight模式 二 Applicability UsetheFlyWeightpatternwhenallofthefollowingaretrue Anapplicationusesalargenumberofobjects Storagecostsarehighbecauseofthesheerquantityofobjects Mostobjectstatecanbemadeextrinsic Manygroupsofobjectsmaybereplacedbyrelativelyfewsharedobjectsonceextrinsicstateisremoved Theapplicationdoesn tdependonobjectidentity Sinceflyweightobjectsmaybeshared identitytestswillreturntrueforconceptuallydistinctobjects FlyWeight模式 三 Struct FlyWeight模式 四 Struct 续 Participantsclient flyweight concreteFlyweight FlyweightFactory UnsharedConcreteFlyweightCollaborations FlyWeight模式 五 Evaluation把对象的状态分开 intrinsicandextrinsic节约存储空间 内部状态的共享节约了大量空间 外部状态可通过计算获得从而进一步节约空间flyweight与composite结合 Flyweight为leaf节点 并且父节点只能作为外部状态ImplementationRemovingextrinsicstate 尽可能做到实时计算 通过一个小的数据结构 Managingsharedobjects 客户不能直接实例化flyweight 必须通过管理器 例如FlyweightFactory flyweight的生命周期管理 引用计数和回收 FlyWeight模式 六 RelatedPatterns与Composite模式组合可以用flyweight实现State和Strategy模式中的对象ExamplesExcel中cell的管理IOleItemContainer接口允许客户发现每一个cell对象用flyweight实现cell对象 tearoff技术对状态的有效管理是对象技术的一个进步 DesignPatterns 中提到的文档编辑器的例子 StructuralPatterns Decorator StructuralPatterns Proxy Structuralpatterns小结 Adapter bridge facadeadapter用于两个不兼容接口之间的转接bridge用于将一个抽象与多个可能的实现连接起来facade用于为复杂的子系统定义一个新的简单易用的接口composite decorator和proxycomposite用于构造对象组合结构decorator用于为对象增加新的职责proxy为目标对象提供一个替代者flyweight针对细粒度对象的一种全局控制手段 BehavioralPatterns ChainofResponsibility CommandInterpreter IteratorMediator Memento ObserverState StrategyTemplateMethod Visitor 模式12 Command 一 AliasesAction Transactionfunctor functionobject IntentEncapsulatearequestasanobject therebylettingyouparameterizeclientswithdifferentrequests queueorlogrequests andsupportundoableoperations Motivation把请求信息和请求执行过程封装起来framework往往需要把命令请求与处理请求的对象分开 command模式可以把调用操作的对象与操作的目标对象分开允许通过多种途径调用同一个请求 请求的重用 Command模式 二 Applicability UsetheCommandpatternwhen parameterizeobjectsbyanactiontoperform 代替回调specify queue andexecuterequestsatdifferenttimessupportundosupportloggingchangessothattheycanbereappliedincaseofasystemcrashstructureasystemaroundhigh leveloperationsbuiltonprimitivesoperations transactions Command模式 三 StructParticipantsClient Command ConcreteCommand Invoker Receiver Command模式 四 Collaborations Command模式 五 EvaluationCommanddecouplestheobjectthatinvokestheoperationfromtheonethatknowshowtoperformit Commandsarefirst classobjects Theycanbemanipulatedandextendedlikeanyotherobject Youcanassemblecommandsintoacompositecommand AnexampleisMacroCommand It seasytoaddnewCommands becauseyoudon thavetochangeexistingclasses ImplementationHowintelligentshouldacommandbe SupportingundoandredoAvoidingerroraccumulationintheundoprocessUsingC templates Command模式 六 RelatedPatternsComposite模式可用来实现command组合为实现undo redo 可以用其他行为模式来管理状态 如memento模式 Command被放到historylist之前 可以用prototype模式复制自身Examples 模式13 Iterator 一 Aliases CursorIntentProvideawaytoaccesstheelementsofanaggregateobjectsequentiallywithoutexposingitsunderlyingrepresentation MotivationAnaggregateobjectsuchasalistshouldgiveyouawaytoaccessitselementswithoutexposingitsinternalstructure SeparatingthetraversalmechanismfromtheListobjectletsusdefineiteratorsfordifferenttraversalpolicieswithoutenumeratingthemintheListinterface Iterator模式 二 Applicability UsetheIteratorpatternwhen toaccessanaggregateobject scontentswithoutexposingitsinternalrepresentation tosupportmultipletraversalsofaggregateobjects toprovideauniforminterfacefortraversingdifferentaggregatestructures thatis tosupportpolymorphiciteration Iterator模式 三 StructParticipantsIterator ConcreteIterator Aggregate ConcreteAggregateCollaborations Iterator模式 四 EvaluationItsupportsvariationsinthetraversalofanaggregateIteratorssimplifytheAggregateinterfaceMorethanonetraversalcanbependingonanaggregateImplementation实现可以非常灵活Whocontrolstheiteration externaliteratorversusinternaliteratorWhodefinesthetraversalalgorithm Aggregate本身定义算法 Cursormodeiterator定义算法 iterator如何访问数据Howrobustistheiterator Iterator模式 五 Implementation 续 AdditionalIteratoroperations 基本操作 First Next IsDone andCurrentItemUsingpolymorphiciterators iterator资源释放IteratorsmayhaveprivilegedaccessIteratorsforcomposites 适合于internaliterator或者cursor方式的iteratorNulliterators Iterator模式 六 RelatedPatternsComposite iterator常被用于composite模式的复合结构PolymorphiciteratorsrelyonfactorymethodstoinstantiatetheappropriateIteratorsubclass ExamplesCOMenumerator connectableobject ADO OLEDBC STL在STL中 iterator是连接algorithm和container的桥梁 模式14 Observer 一 Aliases Dependents Publish SubscribeIntentDefineaone to manydependencybetweenobjectssothatwhenoneobjectchangesstate allitsdependentsarenotifiedandupdatedautomatically Motivation把系统分成一些相互关联的类或者对象 如何维护这些类的实例一致性 ThekeyobjectsinthispatternaresubjectandobserverOne to manyrelationshipAsubjectmayhaveanynumberofdependentobservers Allobserversarenotifiedwheneverthesubjectundergoesachangeinstate Observer模式 二 Applicability UsetheObserverpatternwhen Whenanabstractionhastwoaspects onedependentontheother Encapsulatingtheseaspectsinseparateobjectsletsyouvaryandreusethemindependently Whenachangetooneobjectrequireschangingothers andyoudon tknowhowmanyobjectsneedtobechanged Whenanobjectshouldbeabletonotifyotherobjectswithoutmakingassumptionsaboutwhotheseobjectsare Inotherwords youdon twanttheseobjectstightlycoupled Observer模式 三 StructParticipantsSubject ConcreteSubject Observer ConcreteObserver Observer模式 四 Collaborations Observer模式 五 EvaluationAbstractcouplingbetweenSubjectandObserverSupportforbroadcastcommunicationUnexpectedupdatesImplementationMappingsubjectstotheirobservers ObservingmorethanonesubjectWhotriggerstheupdate Clientorsubject MakingsureSubjectstateisself consistentbeforenotificationsubject向observer传递变化信息中间插入ChangeManager Observer模式 六 RelatedPatternsMediator 用Mediator模式封装复杂的更新语义ExamplesCOMpropertypageCOM EventModel MVC 模式15 Strategy 一 Aliases PolicyIntentDefineafamilyofalgorithms encapsulateeachone andmaketheminterchangeable Strategyletsthealgorithmvaryindependentlyfromclientsthatuseit Motivation有些算法对于某些类是必不可少的 但是不适合于硬编进类中 客户可能需要算法的多种不同实现 允许增加新的算法实现或者改变现有的算法实现我们可以把这样的算法封装到单独的类中 称为strategy Strategy模式 二 Applicability UsetheStrategypatternwhen manyrelatedclassesdifferonlyintheirbehavior youneeddifferentvariantsofanalgorithm analgorithmusesdatathatclientsshouldn tknowabout aclassdefinesmanybehaviors andtheseappearasmultipleconditionalstatementsinitsoperations Strategy模式 三 StructParticipantsStrategy ConcreteStrategy ContextCollaborationsStrategyandContextinteracttoimplementthechosenalgorithmAcontextforwardsrequestsfromitsclientstoitsstrategy Strategy模式 四 EvaluationFamiliesofrelatedalgorithmsAnalternativetosubclassingStrategieseliminateconditionalstatementsClientsmustbeawareofdifferentStrategiesCommunicationoverheadbetweenStrategyandContextIncreasednumberofobjectsImplementationDefiningtheStrategyandContextinterfacesStrategiesastemplateparametersMakingStrategyobjectsoptional Strategy模式 五 RelatedPatternsflyweight 考虑用flyweight模式来实现strategy对象ExamplesATL中COM对象的线程模型支持 模式16 Visitor 一 IntentRepresentanoperationtobeperformedontheelementsofanobjectstructure Visitorletsyoudefineanewoperationwithoutchangingtheclassesoftheelementsonwhichitoperates Motivation为了把一个操作作用于一个对象结构中 一种做法是把这个操作分散到每一个节点上 导致系统难以理解 维护
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 海洋科技公司年终总结报告
- 芒果包装材料选择与设计方案
- 废弃矿山重度污染土壤修复方案
- 泉州市中医院消化系统急症考核
- (2025年)食品安全总监、食品安全员考核考试试题库(含答案)
- 高标准农田农业环境监测方案
- 无锡市中医院心电图伪差识别考核
- 南京市中医院并发症统计分析考核
- 生产过程风险控制方案
- 道路景观绿化施工标准
- 2025年陕西省招聘社区工作者考试应知应会题库(附答案)
- 2025版安全生产法
- 《教师职业道德与专业发展》自考试题及答案(一)
- 商场消防安全用电知识培训课件
- 《基层常见病诊疗指南》
- 货运信息中介公司领导管理细则
- 2025年中国出版集团有限公司校园招聘笔试参考题库附带答案详解
- 集装箱驾驶员管理制度
- 电视纪录片拍摄的策划方案
- DB41∕T 727-2021 雷电防护装置检测应检部位确定
- 产科四步触诊教学课件
评论
0/150
提交评论