第7章(2)详细设计与PSM建模技术-OO设计原理_第1页
第7章(2)详细设计与PSM建模技术-OO设计原理_第2页
第7章(2)详细设计与PSM建模技术-OO设计原理_第3页
第7章(2)详细设计与PSM建模技术-OO设计原理_第4页
第7章(2)详细设计与PSM建模技术-OO设计原理_第5页
已阅读5页,还剩74页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第7章(2)PSM模型及其设计

OO设计原理与设计模式宁夏医科大学理学院杨德仁大纲PSM建模技术简介问题:变化是硬道理,应对是必须的OODesignTopPrinciplesOverviewofPatternsGRASP模式及其9个具体模式Demeter法则新对象:虚拟软件对象InheritancerelatedPrinciplesOtherUsefulDesignPrinciples*SOLIDPrinciples(是GRASP的抽象?)体系结构设计原理References2OODesignTopPrinciples应对变化:隔离变化ProtectedVariationsIncreasecohesionwherepossibleSeparationofconcernsFocusedexpertsDecreasecouplingwherepossibleKeepInheritanceaslessaspossibleSimplifyinterfacesReduceconnectionsinnumberandvolumeEmployandsupportreuseReuseexistingdesignsandcodewherepossibleIncreasereusabilitywherepossibleOODesignTopPrinciplesWhatiftheprinciplesconflictwitheachother?AgoodclassdecompositionmayhavetoomanyconnectionsbetweenclassesStrongencapsulationmayleadtoperformancepenalties惩罚Howcanwereliably可靠followtheprinciples?Standoneachothers'shoulders,noteachothers'toes.Learnfrompreviousdesigners(的设计模式)Thecriticaldesigntoolforsoftwaredevelopmentisamindwelleducatedin

designprinciplesandpatterns.Alargesetofsoftprinciples,designpatternexample,andpractice,casestudywillhelptoimproveyourdesignskills设计模式:用以命名、表示和记忆一些基本的和经典的设计思想OverviewofPatternsIn

softwareengineering,a

designpattern

isageneralreusablesolutiontoacommonlyoccurringproblemwithinagivencontextin

softwaredesign.Apatternisarecurring

solutiontoastandardproblem,inacontext.对问题、解决方案的命名化描述,解决相似问题的通用方法。用来命名、表示和记忆经典的设计思想数学家说:世界是无限的,但模式是有限的。Adesignpatternisnotafinisheddesignthatcanbetransformeddirectlyinto

source

or

machine

code.Itisadescriptionortemplateforhowtosolveaproblemthatcanbeusedinmanydifferentsituations.Patternsareformalized

bestpractices

thattheprogrammerhimselfmustimplementintheapplication.Object-oriented

designpatternstypicallyshowrelationshipsand

interactions

between

classes

or

objects,withoutspecifyingthefinalapplicationclassesorobjectsthatareinvolved.Designpatternsresideinthedomainofmodulesandinterconnections.Atahigherlevelthereare

architecturalpatterns

thatarelargerinscope,usuallydescribinganoverallpatternfollowedbyanentiresystem.PresentsolutionstocommonsoftwareproblemsarisingwithinacertaincontextOverviewofPatternsCapturerecurringstructures&dynamicsamongsoftwareparticipantstofacilitatereuseofsuccessfuldesignsTheProxyPattern11ProxyserviceServiceserviceAbstractServiceserviceClientHelpresolvekeysoftwaredesignforcesFlexibilityExtensibilityDependabilityPredictabilityScalabilityEfficiencyGenerallycodifyexpertknowledgeofdesignstrategies,constraints&“bestpractices”GRASPpatternsGRASPisanacronymcreatedbyCraigLarmantoencompassnineobjectorienteddesignpatternsAcollectionofgeneralobjected-orienteddesignpatterns(orPrinciples)areusedtoassignresponsibilitytoobjectsAntempttodocumentwhatexpertdesignersprobablyknowintuitivelyGRASPnamesanddescribessomebasicprinciplestoassignresponsibilities-tosupportRDDGRASPguideschoicesaboutassigningresponsibilities.CanbeappliedwhiledrawingUMLinteractiondiagramsandwhilecoding.offersbenefitssimilartotheclassic“GangofFour”patternsUMLforOOdesignvisualmodeling,duringwhichtimebothGRASPandGoFpatternscanbeapplied.Assuch,theiruseresultsinaRDDforObjectOrientation(OO)–Contrastto(themoretraditional)Data‐DrivenDesignGRASPpatternsGRASP解析:通用责任分配软件模式(首字符组成)GeneralResponsibilityAssignmentSoftwarePatternsGeneral:Abstract,i.e.widelyapplicableforvarietyofsituationsResponsibility:Obligations,duties各司其职统一协调,相互协作Assignment:Givingaresponsibilitytoamodulemodule?capabilitytocarryoutresponsibilitystructureandmethodsSoftware:ComputercodePatterns:Regularities,templates,abstractionGRASPpatternsGRASP有助于决定把责任分配给哪些对象/类。FundamentalPrinciplesofObjectDesign,核心思想/理念各尽其责(职责内聚),相互协作(松散耦合)从问题域中识别对象及其责任,确定对象交互。LRG:软件对象要尽量接近现实世界的事物,以降低表示差异,进而降低软件的复杂度。Domainmodelillustratesattributesandassociationsinspiresthe“knowing”responsibilities为对象定义蓝图即通过(具有方法的)类去实现责任。GRASP

patternsGoal:UseGRASPasatooltohelpmasterthebasicsofOODandunderstandingresponsibilityassignmentinobjectdesign.指导把责任分配给对象或参与协作的(多个)对象共同体9种模式信息专家

创建者高内聚

低耦合控制器间接性

纯虚构多态性

预防变化其中,高内聚与低耦合模式是GRASP其它模式的根本。GRASPpatterns

搞清对象职责各司其职降低耦合Assignaresponsibilitysothatcouplingremainslowandcohesionremainshigh.Usethisprincipletoevaluatealternatives.目的:分配职责使耦合性尽可能低。减少类或模块之间的交互复杂度(接口数量,参数数据),提高模块的“可重用性”和“移植性”顶层原理:高内聚、低耦合(HighCohesion、LowCoupling)。内聚:类或模块独立完成功能的能力,不依赖于外部代码。耦合:类或模块之间联系的紧密程度;联系越紧密,耦合度越高,牵一发而动全身。高内聚和低耦合伴随出现:内聚程度越高,耦合度就越低。GRASP:信息专家(Expert)问题:给对象分配职责的通用原则是什么?解决方案:将职责分配给拥有履行一个职责所必需信息的类(信息专家)。职责执行需要某些信息,把职责分配给该信息的拥有者。高内聚或将与其它对象协作来完成其责任(信息分布于不同对象上)。低耦合分析:信息专家模式是面向对象设计的最基本原则。服务跟着属性走在系统设计时,需要将职责分配给具有实现这个职责所需要信息的类。认知和行为责任:知其责,而行其事:类只干该干的事情,不该干的事情不干。相关模式:DoItYourself(DIY)对应于SOLID中的单一职责原则。Exampleforexpert假设我们需要获得VideoStore的所有videos。因VideoStore知道其所有videos,我们能把此责任指派给VideoStore类。VideoStore就是信息专家GRASP:创建者(Creator)谁负责创建对象(类实例化)?基于对象间关联及其交互,决定谁能成为创建者:容器:包含者或聚集者记录者紧密使用者具有初始化数据者支持低耦合:基于已有的关联、可见性行为职责相关模式?GOF中的工厂模式实例:考虑录像店中的VideoStore和VideoVideoStore和Video有聚集关联关系,即VideoStore是容器,Video是被包含的对象可以在VideoStore类中实例化Video对象GRASP:创建者(Creator)GRASP:低耦合(LowCoupling)问题:依赖者随被依赖而变化,如何减少变更带来的影响,提高重用性?方案:分配责任,使得耦合水平降低。即保持低耦合Cohesion,耦合元素可以是类,也可以是模块、子系统或者系统。耦合评价系统中各个元素之间连接或依赖强弱关系的尺度,元素的职责相关性和集中度的体现;元素之间连接、感知及依赖程度的度量两个元素被耦合,如果某元素聚合(组合)于另一元素,或实现/扩展其他元素。分析:低耦合有助于系统可维护性、高效率和代码可重用性。具有低耦合的元素不过多依赖其他元素。独立性,有利于重用。适应需求变化,一旦发生变化时,可以把影响缩小到最小范围。高耦合类过多地依赖其他类。这种设计将会导致:类的修改导致其他类产生较大影响;系统难以维护和理解;系统重用性差,在重用高耦合的类时不得不重用它所依赖的其他类。因此需要对高耦合的系统进行重构。相关模式:预保护的变异、信息专家支持低耦合GRASP:高内聚(HighCohesion)问题:怎样使得复杂性可管理?使得变化可管理?方案:分配职责,使得元素保持高内聚。元素的一些操作如何在功能上相关?清楚地定义该元素的目的把相关责任存放在一个单元:实现高内聚优点:降低复杂性,容易理解和维护;代码复用;低耦合为了达到高内聚,需要对类进行分解,使得类具有独立职责,满足单一职责原则。在类中只保留一组相关的属性和方法,只处理与之相关的功能;类将与其他类协作完成复杂的任务:需要在多个类中重用的属性和方法或完成其他功能所需的属性和方法封装在其他类中。分析:内聚是评价元素的职责被关联和关注强弱的尺度。如果元素具有很多紧密相关的职责,而且只完成有限的功能,则这个元素就具有高内聚性。需要控制类的粒度,在分配类的职责时使其内聚保持为最高,提高类的重用性,控制类设计的复杂程度。而低内聚类会执行很多互不相关的操作,这将导致系统难于理解、难于重用、难于维护、过于脆弱,容易受到变化带来的影响。相关模式:模块化设计和两个相关的Solid原理,即

“SingleResponsibilityPrinciple,”addresseshighcohesionintheclasslevel“InterfaceSegregationPrinciple,”addresseshighcohesionintheinterfacelevelGRASP:高内聚(HighCohesion)18ExampleforpoorcouplingGRASP:控制器(Controller)问题:请求来自于UI层对象时,哪个对象优先接收请求?即谁应该负责处理输入系统事件?方案:把处理系统事件的职责分配/委派给专门类,这个类可以代表:整个系统、设备或者子系统;系统事件发生时对应的用例场景,在相同用例场景中使用相同控制器来处理所有的系统事件。分析接收UI层对象的请求,并把工作委托给其他类,它只负责协调和控制,本身不完成太多的功能。然后控制/协调领域层对象来实现该请求Actor产生UI事件;UI对象必须响应该事件MVC原则,UI对象不应该包含应用或业务逻辑,应把请求委派给模型(实体对象?)(协调)相关模式:命令、外观、层、纯虚构GRASP:控制器(Controller)对象作为控制器,如果该对象代表整个系统(facadecontroller)该对象代表某用例,处理一系列操作sessioncontroller一般而言,控制器只协调或控制这些活动本身不做大量工作把工作委派给其它对象优点能够复用该控制器类用以维护该用例的状态能够控制活动的序列GRASP:控制器(Controller)思考题此控制器与鲁棒图中的控制对象的区别?防止BloatedControllers控制器类被称为臃肿的,如果该类被重载(overloaded)了太多责任。控制器类执行了很多任务解决方案增加更多控制器,这些任务本该委托给其他类。每个类都有所专长,各司其职。GRASP:多态性(Polymorphism)问题:基于元素类型,如何实现基于类型的选择?如何创建可嵌入的软件组件?多态:指导决定哪个对象负责处理这些变化的元素当选择或行为随类型(类)变化时,用多态操作为变化的行为类型分配责任把各变化的“行为”定义职责分别分配给具有相同操作行为界面的通用接口的实现子类,利用多态性适应行为的可变性。由条件变化引发同一类型的不同行为是程序的基本主题。用条件语句设计程序,当系统发生变化时,必须修改程序逻辑,致使难以扩展程序。对于C/S可视化组件,在不影响客户端的前提下,将服务器的一个组件替换为另一个。优点:避免重复代码;避免重复分支条件;易扩展,只要实现了统一的通用接口,便可实现行为扩展多态,子类对象可覆盖父类对象的行为,以适应变化,使变化点能够“经得起未来验证”。相关:Grasp:受保护的变异,GoF:适配器,命令,组合,代理,状态(组合、观察者)、策略GRASP:多态性(Polymorphism)示例:绘图程序问题:支持可以画不同类型的图形,允许扩展使用多态实现,符合高内聚和低耦合原则客户代码针对同一接口(Shape)发出Draw消息,具体实例绘制出不同的图形。

扩展:增加了一个菱形(Diamond)类,继承Shape,对使用Shape客户代码没有影响。GRASP:纯虚构(PureFabrication)问题:为领域对象分配职责会导致不良内聚或耦合,而专家原则提供的方案不合适。谁来负责处理这种情况?方案设计虚构类,分配一组高内聚职责该类不代表领域的概念,是凭空虚构的理想情况:虚构类的职责支持高内聚低耦合把非问题领域中的职责分配给人工定义的类,把与域对象无关的一套相关责任(responsibilitiesthatdoesn‘trepresentanydomainobject)分配给虚拟类,如DAO。优点:高内聚,低耦合,可以复用该类。分析消除了信息专家模式带来的低内聚和高耦合的坏设计,得到具有更好重用性的设计。在系统中引入抽象类或接口来提高系统的扩展性也可以认为是纯虚构模式的一种应用。纯虚构模式通常基于相关功能的划分,是一种以功能为中心的对象或行为对象。相关:实现低耦合和高内聚(系统设计地终极目标)的一个保证其它模式如Adapter、Strategy和命令

GRASP:纯虚构(PureFabrication)实例1假设Shape类,拟把shape数据存储在数据库中若把该责任放入Shape类中,将有许多与数据库相关的操作,从而使Shape无内聚力。因此,创造人为类DBStore,令其负责执行所有的数据库操作。同样日志(log)接口负责记录logging信息,也是纯虚构的实例在数据库中保存Sale类保存Sale实例:根据信息专家,职责应分配给Sale造成问题:会造成Sale与数据库接口类耦合面向数据库的操作与实际的销售概念无关,使得Sale非内聚。不利于数据库操作的复用,其他类也存在保存对象职责解决方法:虚构一新类PersitentStorage,负责Sale的存储优点:使用Sale保持高内聚和低耦合;PersitentStorage本身也相对内聚;可以设计PersitentStorage为通用的对象GRASP:纯虚构(PureFabrication)设计类的产生表示解析,是对象设计的常见策略如Sale对象,根据领域对象的事物分析而得支持低表示差异目标行为解析将相关的行为或方式组织在一起如某个问题的算法,类是行为的组合纯虚构基于相关功能性,以功能为中心构造对象禁忌不要滥用行为解析及纯虚构对象,导致大量行为对象,功能变为对象GRASP:间接性/中介(Indirection)问题:如何避免类之间的直接关联(耦合),如何解耦对象以降低耦合度并提高系统的重用性?该给哪种类分配“关联”责任?方案:引入中间对象(中介,Indirection),后者分别与其它单元通信,从而使其它单元之间不再直接耦合分配职责给中间对象以协调组件或服务之间的操作,使得它们不直接耦合。中间对象就是在其他组件之间建立的中介,避免直接耦合。分析:要避免对象之间的直接耦合,最常用的做法是在对象之间引入一个中间对象或中介对象,通过中介对象来间接相连。相关性:Grasp受保护的变化、低耦合中介模式对应于面向对象设计原则中的迪米特法则,GOF模式:Adapter,Facade,Obserever,Mediator、桥GRASP:间接性/中介(Indirection)用多态性说明Indirection?Employee类为系统的其他单元提供了indirection层GRASP:预防变异(ProtectedVariations)问题:如何分配职责给对象、子系统和系统,使得这些元素中的变化或不稳定的点不会对其他元素产生不利影响?解决方案:用稳定的接口来应对可能的变化或其它不安定因素。找出预计有变化或不稳定的元素,为其创建稳定的“接口”而分配职责。用稳定的、定义良好的接口来承担该职责,对其他单元不会有影响预先识别不稳定的变化点,定义稳定的接口如果未来发生变化时,可以通过接口扩展新的功能,而不需要去修改原来旧的实现。优点:提供了应变能力(可维护性和扩展性),高内聚,低耦合。在具体实现时,为了符合受保护变化模式,我们通常需要对系统进行抽象化设计,定义系统的抽象层,再通过具体类来进行扩展。如果需要扩展系统的行为,无须对抽象层进行任何改动,只需要增加新的具体类来实现新的业务功能即可,在不修改已有代码的基础上扩展系统的功能。GRASP:预防变异(ProtectedVariations)Principle:封装变化(change)(顶层原理)第一版中为:Demeter定律(不要和陌生人说话)在软件领域内,唯一不变的就是“变化”,在设计中要考虑的重要因素是变化,为了应对因最初设计考虑不周或需求变动引起的变化如何设计对象、系统和子系统,使其内部的变化或者不稳定因素不会对其他元素产生不良影响?重要的设计原则是封装变化:识别程序中的可变部分。即针对变化,只需要修改该部分。面向对象优点除了代码复用,易维护,效率高外,还有便于重构(Refactor),封装变化就便于重构。实现机制预计识别不稳定的因素,在其外部创建稳定的接口。例如:旅行时,坐汽车是不稳定因素,也许会还坐飞机或者火车,因此,就要把坐汽车抽象成“交通工具”接口。GRASP:预防变异(ProtectedVariations)相关性信息隐藏、open-closed原则,LSP替代原则(?)它与OCP相对应,即在不修改原有元素前提下扩展元素的功能。开闭原则即“可变性封装原则(PrincipleofEncapsulationofVariation,EVP)”,要求找到系统的可变因素并将其封装起来。是其它的基础:多态,数据封装,接口,间接性大多数设计原则和GoF模式都是受保护变化模式的体现。LSP对接口的不同实现或扩展超类的子类对预防变异做了形式化说明RelatedtoOpen-ClosedPrinciple(inSolid):Softwareentities(classes,modules,functions,etc.)shouldbeopenforextensionoradaption,butbeclosedformodificationTochangebehavior,addnewcoderatherthanchangingexistingcode示例:“一国两制”是开放封闭原则的应用。前提:不改变大陆原有社会主义制度,在回归时,特区实行资本主义制度。31Demeter法则不要和陌生人说话(只跟直接依赖的对象通信)。防止耦合ProposedbyIanHollandin1987,又称为封锁信息原则,Compositereuseprinciple,leastknowledgeprinciple(onlytalktoyourimmediatefriends)只与朋友说话,不与陌生人说话。若要与陌生人通话,则通过双方都认识的人,由其转发。中介?在编程中体现“useonlyonedot”。Inparticular,anobjectshouldavoidinvokingmethodsofamemberobjectreturnedbyanothermethod.不要历经远距离的对象结构路径访问远距离间接对象解决方法,需要对”熟人”对象增加新的公共操作LawofDemetergovernsthecommunicationstructurewithinanobject-orienteddesignrestrictsmessage-sendingstatementsinmethodimplementationsonlytalktoyourimmediatefriendsmessagetargetcanonlybeoneofthefollowingobjects:themethod'sobjectitself(C++,Java,C#:this;Smalltalk:self,super;VB.NET:Me)anobjectthatisanargumentinthemethod'ssignatureanobjectreferredtobytheobject'sattributeanobjectcreatedbythemethodanobjectreferredtobyaglobalvariableDemeter法则Moreformally,theLawofDemeterforfunctionsrequiresthatamethodMofanobjectOmayonlyinvokethemethodsofthefollowingkindsofobjects:OitselfM’sparametersanyobjectscreated/instantiatedwithinM

O’sdirectcomponentobjectsPeterVanRooijenpostedthefollowingdescriptionoftheLawOfDemetertoUsenet:Youcanplaywithyourself.Youcanplaywithyourowntoys(butyoucan'ttakethemapart),Youcanplaywithtoysthatweregiventoyou.Andyoucanplaywithtoysyou'vemadeyourself.ExplanationinplainEnglish:YourmethodcancallothermethodsinitsclassdirectlyYourmethodcancallmethodsonitsownfieldsdirectly(butnotonthefields'fields)Whenyourmethodtakesparameters,yourmethodcancallmethodsonthoseparametersdirectly.Whenyourmethodcreateslocalobjects,thatmethodcancallmethodsonthelocalobjects.ButOneshouldnotcallmethodsonaglobalobject(butitcanbepassedasaparameter?)Oneshouldnothaveachainofmessagesa.getB().getC().doSomething()insomeclassotherthana'sclass.InheritancerelatedPrinciplesPrinciplesonInheritancePrefertype(interface)inheritanceoverclass(implementation)inheritance(前面讲过)Programtotheinterface,nottheimplementation.LiskovSubstitutionprinciple(前面讲过)PrefercompositiontoinheritanceDeferredbindingCost:PerformanceUsedelegationto“simulate”runtimeinheritance.GRASP模式与新对象鲁棒图中的控制器80%转换为类的方法20%以独立软件类存在GRASP模式与新对象GRASP模式中,新对象(非业务对象):来源:控制器几种?软件虚对象纯虚构还来自于:SOLID原理、GoF设计模式?间接中介(减少耦合)在何时引入设计?鲁棒图目的之一是发现新对象GRASP模式与新对象鲁棒图中的两种控制器直接与实体对象相连直接与界面相连,而不与其他控制器相连将转换为实体对象的方法不直接与实体对象相连直接与界面对象和另一控制器相连控制性类:转换为软件虚对象*代理语义:介于actor与对象之间不与界面相连与控制器直接相连,控制器与实体对象相连InheritancerelatedPrinciplesPrincipleFavorCompositionOverInheritanceCompositionMethodofreuseinwhichnewfunctionalityisobtainedbycreatinganobjectcomposedofotherobjectsThenewfunctionalityisobtainedbydelegatingfunctionalitytooneoftheobjectsbeingcomposedSometimescalledaggregationorcontainment,althoughsomeauthorsgivespecialmeaningstothesetermsCompositioncanbe:Byreference(C++)Byvalue(Java)InheritancerelatedPrinciplesForexample:Aggregationwhenoneobjectownsorisresponsibleforanotherobjectandbothobjectshaveidenticallifetimes(GoF)whenoneobjecthasacollectionofobjectsthatcanexistontheirown(UML)Containmentaspecialkindofcompositioninwhichthecontainedobjectishiddenfromotherobjectsandaccesstothecontainedobjectisonlyviathecontainerobject(Coad)InheritancerelatedPrinciplesAdvantagesOfCompositionContainedobjectsareaccessedbythecontainingclasssolelythroughtheirinterfaces"Black-box"reuse,sinceinternaldetailsofcontainedobjectsarenotvisibleGoodencapsulationFewerimplementationdependenciesEachclassisfocusedonjustonetaskThecompositioncanbedefineddynamicallyatrun-timethroughobjectsacquiringreferencestootherobjectsofthesametypeDisadvantagesOfCompositionResultingsystemstendtohavemoreobjectsInterfacesmustbecarefullydefinedinordertousemanydifferentobjectsascompositionblocksInheritancerelatedPrinciplesInheritance/CompositionSummaryBothcompositionandinheritanceareimportantmethodsofreuseInheritancewasoverusedintheearlydaysofOOdevelopmentOvertimewe'velearnedthatdesignscanbemademorereusableandsimplerbyfavoringcompositionOfcourse,theavailablesetofcomposableclassescanbeenlargedusinginheritanceSocompositionandinheritanceworktogetherButourfundamentalprincipleis:FavorCompositionOverInheritanceInheritancerelatedPrinciples要尽量使用合成、聚合,尽量不要使用继承。合成、聚合复用原则:在新对象里面使用已有对象,使之成为新对象的一部份,新对象通过向这些对象的委派达到复用已有功能的目的。合成、聚合有如下好处:新对象存取成分对象的唯一方法是通过成分对象的接口。这种复用是黑箱复用,因为成分对象的内部细节是新对象所看不到的。这种复用可以在运行时间内动态进行,新对象可以动态的引用与成分对象类型相同的对象。合成、聚合可以应用到任何环境中去,而继承只能应用到一些有限环境中去导致错误的使用合成、聚合与继承的常见原因把“Has-a”关系当作“Is-a”关系。如果两个类是“Has-a”关系那么应使用合成、聚合,如果是“Is-a”关系那么可使用继承。InheritancerelatedPrinciplesInheritancerelatedPrinciplesUsedelegationto“simulate”runtimeinheritance.Theterm"inheritance"referstoasituationinwhichattributesand/orbehaviorsarepassedonfromoneobjecttoanother.Runtimeinheritancereferstotheabilitytoconstructtheparent/childhierarchytreeatruntime.WhileJavadoesnotallowthisnatively,thereareanumberofprojectsandtechnologiesavailablethatwillenableyoutomodifythebytecodeofaclassaftercompilation.Whiletheyreallyaren'tintendedtouseforruntimeinheritance,theycoulddothejob.Analternativetonativeruntimeinheritanceisaconceptknownas"delegation",whichreferstoconstructingahierarchyofobject"instances"atruntime.Thistechniquewillallowyoutosimulateruntimeinheritance.InheritancerelatedPrinciplesThe

delegationpattern

isa

designpattern

in

OOP

wherean

object,insteadofperformingoneofitsstatedtasks,delegatesthattasktoanassociatedhelperobject.Thedelegationpatternisoneofthefundamental

abstraction

patternsthatunderlieothersoftwarepatternssuchas

composition

(AKAaggregation),

mixins

and

aspects.Thereisan

InversionofResponsibility

inwhichahelperobject,knownasadelegate,isgiventheresponsibilitytoexecuteataskforthe

delegator.Usedelegationto“simulate”runtimeinheritance.Whenthisoccursatcompile-time,itisusuallycalled"subclassing"sinceoneclass,thechild,islowerthantheparentintheinheritancehierarchy.TheJavaprogramminglanguagereservesthekeyword“extends”forcompile-timeinheritance.OtherUsefulDesignPrinciplesJEDUF有些需求易于变化,前面的大设计(BigDesignUpFront)浪费时间Overlycomplicatedand/orgoldplatingJustEnoughDesignUpFront(JEDUF)适可而止,防止设计臃肿别杞人忧天OtherUsefulDesignPrinciplesYAGNIYouAin’tGonnaNeedItXPversionofYagniis:Alwaysimplementthingswhenyouactuallyneedthem,neverwhenyoujustforeseethatyouneedthemComparedwithJEDUF?优势WithoutfutureproofingOtherUsefulDesignPrinciplesDRYTheDRY(Don'tRepeatYourself)Principle,alsoknownas“SinglePointControl”or“SingleSourceofTruth”,itstates:Everypieceofknowledgemusthaveasingle,unambiguous,authoritativerepresentationwithinasystem.reducingrepetitionofinformationofallkinds实现机制:Lotsoflittlepieces:“Goodcodeinvariablyhassmallmethodsandsmallobjects.Onlybyfactoringthesystemintomanysmallpiecesofstateandfunctioncanyouhopetosatisfythe‘onceandonlyonce’rule(OOO).”“Inaprogramwrittenwithgoodstyle,everythingissaidonceandonlyonce.”Divideprogramintomethodsthatperformoneidentifiabletask.Keepalloftheoperationsinamethodatthesamelevelofabstraction.Thiswillnaturallyresultinprogramswithmanysmallmethods,eachafewlineslong.优势:增加可维护性和可测试性重构:提取(超)类、方法实际上是软件工程基本原理49OtherUsefulDesignPrinciplesKISSprincipleKISS

isan

acronym

for“Keepitsimple,stupid”asadesignprinciplenotedbythe

U.S.Navy

in1960,andwasinpopularuseby1970.The

KISSprinciple

statesthatmostsystemsworkbestiftheyarekeptsimpleratherthanmadecomplex;therefore

simplicity

shouldbeakeygoalin

design

andunnecessarycomplexityshouldbeavoided.Variationsonthephraseinclude"keepitstupidsimple","keepitshortandsimple","keepitsimplesir","keepitsupersimple","keepitsimpleorbestupid","keepitsimpleandstupid","keepitsimpleandstraightforward","keepitsimpleandsafe","Keepitsimplestudent","keepitsimple,silly","keepitsimpleandsincere"or"keepitsimpleandsecular."SOLID原理Softwaredesignprinciple:Principleprovidesusguideline.Principlesayswhatisrightandwhatiswrong.Itdoesn’tsayushowtosolveproblem.Solid原理(byRobertC.Martin)总结SRPTheSingleResponsibilityPrinciple单一责任原则

OCPTheOpenClosedPrinciple开放封闭原则

LSPTheLiskovSubstitutionPrinciple里氏替换原则

DIPTheDependencyInversionPrinciple依赖倒置原则

ISPTheInterfaceSegregationPrinciple接口分离原则Softwaredesignpattern:Patternisageneralreusablesolutiontoacommonlyoccurringproblemwithinagivencontextinsoftwaredesign.Somepatternsarefactorypattern,Decoratorpatternetc.SOLID原理Designprinciplesarethedesirablegoals

thatoneaimstoachieve.Designpatternsaretoolsonecanusetorealizethosegoals.

Designprinciplesareguidelinestobefollowedthroughoutthesoftwaredevelopmentprocess.Designpatternsarewellacceptedsolutionstorecurringdesignproblems.Inotherwords:

designpatternsemploydesignprinciples.It'sthereforebettertolearndesignprinciplesfirstbecausethenyoucaneasilyunderstandwhat(andwhy)a

pattern

istryingtoachieve.ButDesignPrincipleshavebeenscatteredanddisorganized,andbecameconfusingformany.Mybook"SoftwareDesignPrinciples"isacompilationoftheseprinciplesanduntanglealltheconfusions.TheSingleResponsibilityPrincipleAnobjectshouldhavenomorethanonekeyresponsibility.Ifanobjecthasseveral,unrelatedresponsibilities,thenyouaremissingobjectsinyourdesign!(高耦合)Everyobjectshouldhaveasingleresponsibility,andthatresponsibilityshouldbeentirelyencapsulatedbytheclass.Allitsservicesshouldbenarrowlyalignedwiththatresponsibility.Aclassshouldhaveone,andonlyone,reasontochange.Eachresponsibilityshouldbeaseparateclass,becauseeachresponsibilityisanaxisofchange.Ifachangetothebusinessrulescausesaclasstochange,thenachangetothedatabaseschema,GUI,reportformat,oranyothersegmentofthesystemshouldnotforcethatclasstochange.即要实现表示与业务分离ThechallengewithSRPisgettingthegranularityofaresponsibilityright.责任的定义:即类变化的理由此责任与RDD中的责任有何不同?TheSingleResponsibilityPrincipleSimpleisbeautiful.把复杂事情简单化是智慧!Eachclassshouldhaveonlyoneresponsibilityandfocustodoonesinglething.一个类承担的职责过多,这些职责就耦合。这时一个职责的变化可能会削弱或者抑制该类完成其它职责的能力。这种耦合导致脆弱设计,当变化发生时,设计会遭受到难以预料的破坏Well,thisclearlyconformswithGRASPprincipleofHighCohesion.HighCohesionisanevaluativepatternthatattemptstokeepobjectsappropriatelyfocused,manageableandunderstandableSRPwouldpromotethereuseofcode,clarityandreadability.Yoursystemwouldalsobeeasiertotest,enhanceandmaintained.Developerswouldalsofindlesscontentionforsourcecodefiles.TheSingleResponsibilityPrinciple思考题:此处的责任与责任驱动的责任在语义上是否一致?TheInterfaceSegregationPrincipleInterfacesAdvantages:ClientsareunawareofthespecificclassoftheobjecttheyareusingOneobjectcanbeeasilyreplacedbyanotherLoosenscouplingObjectconnectionsneednotbehardwiredtoanobjectofaspecificclass,therebyincreasingflexibilityIncreaseslikelihoodofreuseImprovesopportunitiesforcompositionsincecontainedobjectscanbeofanyclassthatimplementsaspecificinterfaceDisadvantages:ModestincreaseindesigncomplexityTheInterfaceSegregationPrinciple接口:java中的抽象类和interface类型。

InterfacesAninterfaceisthesetofmethodsoneobjectknowsitcaninvokeonanotherobjectAnobjectcanhavemanyinterfaces.(Essentially,aninterfaceisasubsetofallthemethodsthatanobjectimplements).AtypeisaspecificinterfaceofanobjectDifferentobjectscanhavethesametypeandthesameobjectcanhavemanydifferenttypesAnobjectisknownbyotherobjectsonlythroughitsinterfaceInasense,interfacesexpress"isakindof"inaverylimitedwayas"isakindofthatsupportsthisinterface“增加系统的灵活性,减少了代码量。Interfacesarethekeytopluggability!TheInterfaceSegregationPrincipleInterfaceInheritancevsImplementationInheritanceInterfaceInheritance(Subtyping)-describeswhenoneobjectcanbeusedinplaceofanotherobjectImplementationInheritance(ClassInheritance)-anobject'simplementationisdefinedintermsofanother'sobjectsimplementationTheC++inheritancemechanismmeansbothclassandinterfaceinheritanceC++canperforminterfaceinheritancebyinheritingfromapureabstractclassJavahasaseparatelanguageconstructforinterfaceinheritance-theJavainterfaceJava'sinterfaceconstructmakesiteasiertoexpressandimplementdesignsthatfocusonobjectinterfacesTheInterfaceSegregationPrincipleClientsshouldnotbeforcedtoimplementinterfacestheydon’tuse.即类对其他类的依赖应当建立在最小接口上。Thedependencyofoneclasstoanotheroneshoulddependonthesmallestpossibleinterface.规避通用的涵盖多个业务方法的接口,而用与特定客户类有关的小接口Insteadofonefatinterfacemanysmallinterfacesarepreferredbasedongroupsofmethods,eachoneservingonesub-module.TheInterfaceSegregationPrinciple不能强迫用户去依赖那些他们不使用的接口。如果用户被迫依赖他们不用的接口,当接口发生改变时,他们也不得不跟着改变。用户依赖了自己未用但被其他用户用的接口,当其他用户修改该接口时,依赖该接口的所有用户都将受到影响。违反了开闭原则。使用多个专门的接口比使用单一的总接口总要好。它包含了2层意思:接口设计原则:应遵循最小接口原则,不要把用户不使用的方法塞进同一个接口里。如果一个接口的方法没有被使用到,则说明该接口过胖,应该将其分割成几个功能专一的接口。接口依赖(继承)原则:如果一个接口a依赖(继承)另一个接口b,则接口a相当于继承了接口b的方法,那么继承了接口b后的接口a也应该遵循上述原则:不应该包含用户不使用的方法。反之,则说明接口a被b给污染了,应该重新设计它们的关系。TheInterfaceSegregationPrinciple一个类对另一个类的依赖应该限制在最小化接口上clientshouldnotbeforcedtodependuponinterfacesthattheydon'tuse.接口级别的高内聚(高于类级别)分离关注(SeparationofConcerns)的特例每个接口处理一个具体行为,内聚分离接口有2种方法委托,多重继承实施技术(有时也称为Principle)Programtoaninterface,notanimplementationDependoninterfaces,notconcreteclassesTheInterfaceSegregationPrinciple不应该强迫客户程序依赖于它们不用的方法。接口属于客户,不属于它所在的类层次结构。Martinalsomentionsthat"fatinterfaces"—interfaceswithadditionaluselessmethods—leadtoinadvertentcouplingbetweenclasses.ThisistherealreasonwhytheSIPshouldbeadheredto.详细说明:分离客户就是分离接口接口隔离原则是用来处理胖接口所具有的缺点。如果类接口不是内聚的,就表示该类的接口是胖的,需要减肥.减肥的原则是接口分成多组方法,每组方法都服务于特定客户程序客户程序调用多个具有内聚接口的抽象基类.

TheInterfaceSegregationPrincipleOpen-ClosedPrincipleModulesthatconformtotheOCPmeettwocriteria:OpenForExtension-ThebehaviorofthemodulecanbeextendedtomeetnewrequirementsClosedForModification-theexistingsourcecodeofthemoduleisnotallowedtochangeHowcanwedothis?AbstractionPolymorphismInheritanceInterfaces增加新需求时,可避免rigidity,fragilityandimmobilityOpen-ClosedPrincipleItisnotpossibletohaveallthemodulesofasoftwaresystemsatisfytheOCP,butweshouldattempttominimizethenumberofmodulesthatdonotsatisfyitTheOpen-ClosedPrincipleisreallytheheartofOOdesignConformancetothisprincipleyieldsthegreatestlevelofreusabilityandmaintainability(扩展性和适应性)AcorollarytotheOCPistheSingleChoicePrincipleWheneverasoftwaresystemmustsupportasetofalternatives,ideallyonlyoneclassinthesystemknowstheentiresetofalternativesTheLiskovSubstitutionPrincipleBelongtoSolidprincipleAlsoknownas“Designbycontract”AsubclassshouldhonorthecontractmadebyitparentclassesWhatiswantedhereissomethinglikethefollowingsubstitutionproperty(1988):Ifforeachobjecto1oftypeSthereisanobjecto2oftypeTsuchthatforallprogramsPdefinedintermsofT,thebehavioro

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论