第7章(2)詳細(xì)設(shè)計(jì)與PSM建模技術(shù)-OO設(shè)計(jì)原理_第1頁
第7章(2)詳細(xì)設(shè)計(jì)與PSM建模技術(shù)-OO設(shè)計(jì)原理_第2頁
第7章(2)詳細(xì)設(shè)計(jì)與PSM建模技術(shù)-OO設(shè)計(jì)原理_第3頁
第7章(2)詳細(xì)設(shè)計(jì)與PSM建模技術(shù)-OO設(shè)計(jì)原理_第4頁
第7章(2)詳細(xì)設(shè)計(jì)與PSM建模技術(shù)-OO設(shè)計(jì)原理_第5頁
已閱讀5頁,還剩74頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

第7章(2)PSM模型及其設(shè)計(jì)

OO設(shè)計(jì)原理與設(shè)計(jì)模式寧夏醫(yī)科大學(xué)理學(xué)院楊德仁大綱PSM建模技術(shù)簡介問題:變化是硬道理,應(yīng)對是必須的OODesignTopPrinciplesOverviewofPatternsGRASP模式及其9個(gè)具體模式Demeter法則新對象:虛擬軟件對象InheritancerelatedPrinciplesOtherUsefulDesignPrinciples*SOLIDPrinciples(是GRASP的抽象?)體系結(jié)構(gòu)設(shè)計(jì)原理References2OODesignTopPrinciples應(yīng)對變化:隔離變化ProtectedVariationsIncreasecohesionwherepossibleSeparationofconcernsFocusedexpertsDecreasecouplingwherepossibleKeepInheritanceaslessaspossibleSimplifyinterfacesReduceconnectionsinnumberandvolumeEmployandsupportreuseReuseexistingdesignsandcodewherepossibleIncreasereusabilitywherepossibleOODesignTopPrinciplesWhatiftheprinciplesconflictwitheachother?AgoodclassdecompositionmayhavetoomanyconnectionsbetweenclassesStrongencapsulationmayleadtoperformancepenalties懲罰Howcanwereliably可靠followtheprinciples?Standoneachothers'shoulders,noteachothers'toes.Learnfrompreviousdesigners(的設(shè)計(jì)模式)Thecriticaldesigntoolforsoftwaredevelopmentisamindwelleducatedin

designprinciplesandpatterns.Alargesetofsoftprinciples,designpatternexample,andpractice,casestudywillhelptoimproveyourdesignskills設(shè)計(jì)模式:用以命名、表示和記憶一些基本的和經(jīng)典的設(shè)計(jì)思想OverviewofPatternsIn

softwareengineering,a

designpattern

isageneralreusablesolutiontoacommonlyoccurringproblemwithinagivencontextin

softwaredesign.Apatternisarecurring

solutiontoastandardproblem,inacontext.對問題、解決方案的命名化描述,解決相似問題的通用方法。用來命名、表示和記憶經(jīng)典的設(shè)計(jì)思想數(shù)學(xué)家說:世界是無限的,但模式是有限的。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解析:通用責(zé)任分配軟件模式(首字符組成)GeneralResponsibilityAssignmentSoftwarePatternsGeneral:Abstract,i.e.widelyapplicableforvarietyofsituationsResponsibility:Obligations,duties各司其職統(tǒng)一協(xié)調(diào),相互協(xié)作Assignment:Givingaresponsibilitytoamodulemodule?capabilitytocarryoutresponsibilitystructureandmethodsSoftware:ComputercodePatterns:Regularities,templates,abstractionGRASPpatternsGRASP有助于決定把責(zé)任分配給哪些對象/類。FundamentalPrinciplesofObjectDesign,核心思想/理念各盡其責(zé)(職責(zé)內(nèi)聚),相互協(xié)作(松散耦合)從問題域中識別對象及其責(zé)任,確定對象交互。LRG:軟件對象要盡量接近現(xiàn)實(shí)世界的事物,以降低表示差異,進(jìn)而降低軟件的復(fù)雜度。Domainmodelillustratesattributesandassociationsinspiresthe“knowing”responsibilities為對象定義藍(lán)圖即通過(具有方法的)類去實(shí)現(xiàn)責(zé)任。GRASP

patternsGoal:UseGRASPasatooltohelpmasterthebasicsofOODandunderstandingresponsibilityassignmentinobjectdesign.指導(dǎo)把責(zé)任分配給對象或參與協(xié)作的(多個(gè))對象共同體9種模式信息專家

創(chuàng)建者高內(nèi)聚

低耦合控制器間接性

純虛構(gòu)多態(tài)性

預(yù)防變化其中,高內(nèi)聚與低耦合模式是GRASP其它模式的根本。GRASPpatterns

搞清對象職責(zé)各司其職降低耦合Assignaresponsibilitysothatcouplingremainslowandcohesionremainshigh.Usethisprincipletoevaluatealternatives.目的:分配職責(zé)使耦合性盡可能低。減少類或模塊之間的交互復(fù)雜度(接口數(shù)量,參數(shù)數(shù)據(jù)),提高模塊的“可重用性”和“移植性”頂層原理:高內(nèi)聚、低耦合(HighCohesion、LowCoupling)。內(nèi)聚:類或模塊獨(dú)立完成功能的能力,不依賴于外部代碼。耦合:類或模塊之間聯(lián)系的緊密程度;聯(lián)系越緊密,耦合度越高,牽一發(fā)而動(dòng)全身。高內(nèi)聚和低耦合伴隨出現(xiàn):內(nèi)聚程度越高,耦合度就越低。GRASP:信息專家(Expert)問題:給對象分配職責(zé)的通用原則是什么?解決方案:將職責(zé)分配給擁有履行一個(gè)職責(zé)所必需信息的類(信息專家)。職責(zé)執(zhí)行需要某些信息,把職責(zé)分配給該信息的擁有者。高內(nèi)聚或?qū)⑴c其它對象協(xié)作來完成其責(zé)任(信息分布于不同對象上)。低耦合分析:信息專家模式是面向?qū)ο笤O(shè)計(jì)的最基本原則。服務(wù)跟著屬性走在系統(tǒng)設(shè)計(jì)時(shí),需要將職責(zé)分配給具有實(shí)現(xiàn)這個(gè)職責(zé)所需要信息的類。認(rèn)知和行為責(zé)任:知其責(zé),而行其事:類只干該干的事情,不該干的事情不干。相關(guān)模式:DoItYourself(DIY)對應(yīng)于SOLID中的單一職責(zé)原則。Exampleforexpert假設(shè)我們需要獲得VideoStore的所有videos。因VideoStore知道其所有videos,我們能把此責(zé)任指派給VideoStore類。VideoStore就是信息專家GRASP:創(chuàng)建者(Creator)誰負(fù)責(zé)創(chuàng)建對象(類實(shí)例化)?基于對象間關(guān)聯(lián)及其交互,決定誰能成為創(chuàng)建者:容器:包含者或聚集者記錄者緊密使用者具有初始化數(shù)據(jù)者支持低耦合:基于已有的關(guān)聯(lián)、可見性行為職責(zé)相關(guān)模式?GOF中的工廠模式實(shí)例:考慮錄像店中的VideoStore和VideoVideoStore和Video有聚集關(guān)聯(lián)關(guān)系,即VideoStore是容器,Video是被包含的對象可以在VideoStore類中實(shí)例化Video對象GRASP:創(chuàng)建者(Creator)GRASP:低耦合(LowCoupling)問題:依賴者隨被依賴而變化,如何減少變更帶來的影響,提高重用性?方案:分配責(zé)任,使得耦合水平降低。即保持低耦合Cohesion,耦合元素可以是類,也可以是模塊、子系統(tǒng)或者系統(tǒng)。耦合評價(jià)系統(tǒng)中各個(gè)元素之間連接或依賴強(qiáng)弱關(guān)系的尺度,元素的職責(zé)相關(guān)性和集中度的體現(xiàn);元素之間連接、感知及依賴程度的度量兩個(gè)元素被耦合,如果某元素聚合(組合)于另一元素,或?qū)崿F(xiàn)/擴(kuò)展其他元素。分析:低耦合有助于系統(tǒng)可維護(hù)性、高效率和代碼可重用性。具有低耦合的元素不過多依賴其他元素。獨(dú)立性,有利于重用。適應(yīng)需求變化,一旦發(fā)生變化時(shí),可以把影響縮小到最小范圍。高耦合類過多地依賴其他類。這種設(shè)計(jì)將會導(dǎo)致:類的修改導(dǎo)致其他類產(chǎn)生較大影響;系統(tǒng)難以維護(hù)和理解;系統(tǒng)重用性差,在重用高耦合的類時(shí)不得不重用它所依賴的其他類。因此需要對高耦合的系統(tǒng)進(jìn)行重構(gòu)。相關(guān)模式:預(yù)保護(hù)的變異、信息專家支持低耦合GRASP:高內(nèi)聚(HighCohesion)問題:怎樣使得復(fù)雜性可管理?使得變化可管理?方案:分配職責(zé),使得元素保持高內(nèi)聚。元素的一些操作如何在功能上相關(guān)?清楚地定義該元素的目的把相關(guān)責(zé)任存放在一個(gè)單元:實(shí)現(xiàn)高內(nèi)聚優(yōu)點(diǎn):降低復(fù)雜性,容易理解和維護(hù);代碼復(fù)用;低耦合為了達(dá)到高內(nèi)聚,需要對類進(jìn)行分解,使得類具有獨(dú)立職責(zé),滿足單一職責(zé)原則。在類中只保留一組相關(guān)的屬性和方法,只處理與之相關(guān)的功能;類將與其他類協(xié)作完成復(fù)雜的任務(wù):需要在多個(gè)類中重用的屬性和方法或完成其他功能所需的屬性和方法封裝在其他類中。分析:內(nèi)聚是評價(jià)元素的職責(zé)被關(guān)聯(lián)和關(guān)注強(qiáng)弱的尺度。如果元素具有很多緊密相關(guān)的職責(zé),而且只完成有限的功能,則這個(gè)元素就具有高內(nèi)聚性。需要控制類的粒度,在分配類的職責(zé)時(shí)使其內(nèi)聚保持為最高,提高類的重用性,控制類設(shè)計(jì)的復(fù)雜程度。而低內(nèi)聚類會執(zhí)行很多互不相關(guān)的操作,這將導(dǎo)致系統(tǒng)難于理解、難于重用、難于維護(hù)、過于脆弱,容易受到變化帶來的影響。相關(guān)模式:模塊化設(shè)計(jì)和兩個(gè)相關(guān)的Solid原理,即

“SingleResponsibilityPrinciple,”addresseshighcohesionintheclasslevel“InterfaceSegregationPrinciple,”addresseshighcohesionintheinterfacelevelGRASP:高內(nèi)聚(HighCohesion)18ExampleforpoorcouplingGRASP:控制器(Controller)問題:請求來自于UI層對象時(shí),哪個(gè)對象優(yōu)先接收請求?即誰應(yīng)該負(fù)責(zé)處理輸入系統(tǒng)事件?方案:把處理系統(tǒng)事件的職責(zé)分配/委派給專門類,這個(gè)類可以代表:整個(gè)系統(tǒng)、設(shè)備或者子系統(tǒng);系統(tǒng)事件發(fā)生時(shí)對應(yīng)的用例場景,在相同用例場景中使用相同控制器來處理所有的系統(tǒng)事件。分析接收UI層對象的請求,并把工作委托給其他類,它只負(fù)責(zé)協(xié)調(diào)和控制,本身不完成太多的功能。然后控制/協(xié)調(diào)領(lǐng)域?qū)訉ο髞韺?shí)現(xiàn)該請求Actor產(chǎn)生UI事件;UI對象必須響應(yīng)該事件MVC原則,UI對象不應(yīng)該包含應(yīng)用或業(yè)務(wù)邏輯,應(yīng)把請求委派給模型(實(shí)體對象?)(協(xié)調(diào))相關(guān)模式:命令、外觀、層、純虛構(gòu)GRASP:控制器(Controller)對象作為控制器,如果該對象代表整個(gè)系統(tǒng)(facadecontroller)該對象代表某用例,處理一系列操作sessioncontroller一般而言,控制器只協(xié)調(diào)或控制這些活動(dòng)本身不做大量工作把工作委派給其它對象優(yōu)點(diǎn)能夠復(fù)用該控制器類用以維護(hù)該用例的狀態(tài)能夠控制活動(dòng)的序列GRASP:控制器(Controller)思考題此控制器與魯棒圖中的控制對象的區(qū)別?防止BloatedControllers控制器類被稱為臃腫的,如果該類被重載(overloaded)了太多責(zé)任。控制器類執(zhí)行了很多任務(wù)解決方案增加更多控制器,這些任務(wù)本該委托給其他類。每個(gè)類都有所專長,各司其職。GRASP:多態(tài)性(Polymorphism)問題:基于元素類型,如何實(shí)現(xiàn)基于類型的選擇?如何創(chuàng)建可嵌入的軟件組件?多態(tài):指導(dǎo)決定哪個(gè)對象負(fù)責(zé)處理這些變化的元素當(dāng)選擇或行為隨類型(類)變化時(shí),用多態(tài)操作為變化的行為類型分配責(zé)任把各變化的“行為”定義職責(zé)分別分配給具有相同操作行為界面的通用接口的實(shí)現(xiàn)子類,利用多態(tài)性適應(yīng)行為的可變性。由條件變化引發(fā)同一類型的不同行為是程序的基本主題。用條件語句設(shè)計(jì)程序,當(dāng)系統(tǒng)發(fā)生變化時(shí),必須修改程序邏輯,致使難以擴(kuò)展程序。對于C/S可視化組件,在不影響客戶端的前提下,將服務(wù)器的一個(gè)組件替換為另一個(gè)。優(yōu)點(diǎn):避免重復(fù)代碼;避免重復(fù)分支條件;易擴(kuò)展,只要實(shí)現(xiàn)了統(tǒng)一的通用接口,便可實(shí)現(xiàn)行為擴(kuò)展多態(tài),子類對象可覆蓋父類對象的行為,以適應(yīng)變化,使變化點(diǎn)能夠“經(jīng)得起未來驗(yàn)證”。相關(guān):Grasp:受保護(hù)的變異,GoF:適配器,命令,組合,代理,狀態(tài)(組合、觀察者)、策略GRASP:多態(tài)性(Polymorphism)示例:繪圖程序問題:支持可以畫不同類型的圖形,允許擴(kuò)展使用多態(tài)實(shí)現(xiàn),符合高內(nèi)聚和低耦合原則客戶代碼針對同一接口(Shape)發(fā)出Draw消息,具體實(shí)例繪制出不同的圖形。

擴(kuò)展:增加了一個(gè)菱形(Diamond)類,繼承Shape,對使用Shape客戶代碼沒有影響。GRASP:純虛構(gòu)(PureFabrication)問題:為領(lǐng)域?qū)ο蠓峙渎氊?zé)會導(dǎo)致不良內(nèi)聚或耦合,而專家原則提供的方案不合適。誰來負(fù)責(zé)處理這種情況?方案設(shè)計(jì)虛構(gòu)類,分配一組高內(nèi)聚職責(zé)該類不代表領(lǐng)域的概念,是憑空虛構(gòu)的理想情況:虛構(gòu)類的職責(zé)支持高內(nèi)聚低耦合把非問題領(lǐng)域中的職責(zé)分配給人工定義的類,把與域?qū)ο鬅o關(guān)的一套相關(guān)責(zé)任(responsibilitiesthatdoesn‘trepresentanydomainobject)分配給虛擬類,如DAO。優(yōu)點(diǎn):高內(nèi)聚,低耦合,可以復(fù)用該類。分析消除了信息專家模式帶來的低內(nèi)聚和高耦合的壞設(shè)計(jì),得到具有更好重用性的設(shè)計(jì)。在系統(tǒng)中引入抽象類或接口來提高系統(tǒng)的擴(kuò)展性也可以認(rèn)為是純虛構(gòu)模式的一種應(yīng)用。純虛構(gòu)模式通?;谙嚓P(guān)功能的劃分,是一種以功能為中心的對象或行為對象。相關(guān):實(shí)現(xiàn)低耦合和高內(nèi)聚(系統(tǒng)設(shè)計(jì)地終極目標(biāo))的一個(gè)保證其它模式如Adapter、Strategy和命令

GRASP:純虛構(gòu)(PureFabrication)實(shí)例1假設(shè)Shape類,擬把shape數(shù)據(jù)存儲在數(shù)據(jù)庫中若把該責(zé)任放入Shape類中,將有許多與數(shù)據(jù)庫相關(guān)的操作,從而使Shape無內(nèi)聚力。因此,創(chuàng)造人為類DBStore,令其負(fù)責(zé)執(zhí)行所有的數(shù)據(jù)庫操作。同樣日志(log)接口負(fù)責(zé)記錄logging信息,也是純虛構(gòu)的實(shí)例在數(shù)據(jù)庫中保存Sale類保存Sale實(shí)例:根據(jù)信息專家,職責(zé)應(yīng)分配給Sale造成問題:會造成Sale與數(shù)據(jù)庫接口類耦合面向數(shù)據(jù)庫的操作與實(shí)際的銷售概念無關(guān),使得Sale非內(nèi)聚。不利于數(shù)據(jù)庫操作的復(fù)用,其他類也存在保存對象職責(zé)解決方法:虛構(gòu)一新類PersitentStorage,負(fù)責(zé)Sale的存儲優(yōu)點(diǎn):使用Sale保持高內(nèi)聚和低耦合;PersitentStorage本身也相對內(nèi)聚;可以設(shè)計(jì)PersitentStorage為通用的對象GRASP:純虛構(gòu)(PureFabrication)設(shè)計(jì)類的產(chǎn)生表示解析,是對象設(shè)計(jì)的常見策略如Sale對象,根據(jù)領(lǐng)域?qū)ο蟮氖挛锓治龆弥С值捅硎静町惸繕?biāo)行為解析將相關(guān)的行為或方式組織在一起如某個(gè)問題的算法,類是行為的組合純虛構(gòu)基于相關(guān)功能性,以功能為中心構(gòu)造對象禁忌不要濫用行為解析及純虛構(gòu)對象,導(dǎo)致大量行為對象,功能變?yōu)閷ο驡RASP:間接性/中介(Indirection)問題:如何避免類之間的直接關(guān)聯(lián)(耦合),如何解耦對象以降低耦合度并提高系統(tǒng)的重用性?該給哪種類分配“關(guān)聯(lián)”責(zé)任?方案:引入中間對象(中介,Indirection),后者分別與其它單元通信,從而使其它單元之間不再直接耦合分配職責(zé)給中間對象以協(xié)調(diào)組件或服務(wù)之間的操作,使得它們不直接耦合。中間對象就是在其他組件之間建立的中介,避免直接耦合。分析:要避免對象之間的直接耦合,最常用的做法是在對象之間引入一個(gè)中間對象或中介對象,通過中介對象來間接相連。相關(guān)性:Grasp受保護(hù)的變化、低耦合中介模式對應(yīng)于面向?qū)ο笤O(shè)計(jì)原則中的迪米特法則,GOF模式:Adapter,Facade,Obserever,Mediator、橋GRASP:間接性/中介(Indirection)用多態(tài)性說明Indirection?Employee類為系統(tǒng)的其他單元提供了indirection層GRASP:預(yù)防變異(ProtectedVariations)問題:如何分配職責(zé)給對象、子系統(tǒng)和系統(tǒng),使得這些元素中的變化或不穩(wěn)定的點(diǎn)不會對其他元素產(chǎn)生不利影響?解決方案:用穩(wěn)定的接口來應(yīng)對可能的變化或其它不安定因素。找出預(yù)計(jì)有變化或不穩(wěn)定的元素,為其創(chuàng)建穩(wěn)定的“接口”而分配職責(zé)。用穩(wěn)定的、定義良好的接口來承擔(dān)該職責(zé),對其他單元不會有影響預(yù)先識別不穩(wěn)定的變化點(diǎn),定義穩(wěn)定的接口如果未來發(fā)生變化時(shí),可以通過接口擴(kuò)展新的功能,而不需要去修改原來舊的實(shí)現(xiàn)。優(yōu)點(diǎn):提供了應(yīng)變能力(可維護(hù)性和擴(kuò)展性),高內(nèi)聚,低耦合。在具體實(shí)現(xiàn)時(shí),為了符合受保護(hù)變化模式,我們通常需要對系統(tǒng)進(jìn)行抽象化設(shè)計(jì),定義系統(tǒng)的抽象層,再通過具體類來進(jìn)行擴(kuò)展。如果需要擴(kuò)展系統(tǒng)的行為,無須對抽象層進(jìn)行任何改動(dòng),只需要增加新的具體類來實(shí)現(xiàn)新的業(yè)務(wù)功能即可,在不修改已有代碼的基礎(chǔ)上擴(kuò)展系統(tǒng)的功能。GRASP:預(yù)防變異(ProtectedVariations)Principle:封裝變化(change)(頂層原理)第一版中為:Demeter定律(不要和陌生人說話)在軟件領(lǐng)域內(nèi),唯一不變的就是“變化”,在設(shè)計(jì)中要考慮的重要因素是變化,為了應(yīng)對因最初設(shè)計(jì)考慮不周或需求變動(dòng)引起的變化如何設(shè)計(jì)對象、系統(tǒng)和子系統(tǒng),使其內(nèi)部的變化或者不穩(wěn)定因素不會對其他元素產(chǎn)生不良影響?重要的設(shè)計(jì)原則是封裝變化:識別程序中的可變部分。即針對變化,只需要修改該部分。面向?qū)ο髢?yōu)點(diǎn)除了代碼復(fù)用,易維護(hù),效率高外,還有便于重構(gòu)(Refactor),封裝變化就便于重構(gòu)。實(shí)現(xiàn)機(jī)制預(yù)計(jì)識別不穩(wěn)定的因素,在其外部創(chuàng)建穩(wěn)定的接口。例如:旅行時(shí),坐汽車是不穩(wěn)定因素,也許會還坐飛機(jī)或者火車,因此,就要把坐汽車抽象成“交通工具”接口。GRASP:預(yù)防變異(ProtectedVariations)相關(guān)性信息隱藏、open-closed原則,LSP替代原則(?)它與OCP相對應(yīng),即在不修改原有元素前提下擴(kuò)展元素的功能。開閉原則即“可變性封裝原則(PrincipleofEncapsulationofVariation,EVP)”,要求找到系統(tǒng)的可變因素并將其封裝起來。是其它的基礎(chǔ):多態(tài),數(shù)據(jù)封裝,接口,間接性大多數(shù)設(shè)計(jì)原則和GoF模式都是受保護(hù)變化模式的體現(xiàn)。LSP對接口的不同實(shí)現(xiàn)或擴(kuò)展超類的子類對預(yù)防變異做了形式化說明RelatedtoOpen-ClosedPrinciple(inSolid):Softwareentities(classes,modules,functions,etc.)shouldbeopenforextensionoradaption,butbeclosedformodificationTochangebehavior,addnewcoderatherthanchangingexistingcode示例:“一國兩制”是開放封閉原則的應(yīng)用。前提:不改變大陸原有社會主義制度,在回歸時(shí),特區(qū)實(shí)行資本主義制度。31Demeter法則不要和陌生人說話(只跟直接依賴的對象通信)。防止耦合ProposedbyIanHollandin1987,又稱為封鎖信息原則,Compositereuseprinciple,leastknowledgeprinciple(onlytalktoyourimmediatefriends)只與朋友說話,不與陌生人說話。若要與陌生人通話,則通過雙方都認(rèn)識的人,由其轉(zhuǎn)發(fā)。中介?在編程中體現(xiàn)“useonlyonedot”。Inparticular,anobjectshouldavoidinvokingmethodsofamemberobjectreturnedbyanothermethod.不要?dú)v經(jīng)遠(yuǎn)距離的對象結(jié)構(gòu)路徑訪問遠(yuǎn)距離間接對象解決方法,需要對”熟人”對象增加新的公共操作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%轉(zhuǎn)換為類的方法20%以獨(dú)立軟件類存在GRASP模式與新對象GRASP模式中,新對象(非業(yè)務(wù)對象):來源:控制器幾種?軟件虛對象純虛構(gòu)還來自于:SOLID原理、GoF設(shè)計(jì)模式?間接中介(減少耦合)在何時(shí)引入設(shè)計(jì)?魯棒圖目的之一是發(fā)現(xiàn)新對象GRASP模式與新對象魯棒圖中的兩種控制器直接與實(shí)體對象相連直接與界面相連,而不與其他控制器相連將轉(zhuǎn)換為實(shí)體對象的方法不直接與實(shí)體對象相連直接與界面對象和另一控制器相連控制性類:轉(zhuǎn)換為軟件虛對象*代理語義:介于actor與對象之間不與界面相連與控制器直接相連,控制器與實(shí)體對象相連InheritancerelatedPrinciplesPrincipleFavorCompositionOverInheritanceCompositionMethodofreuseinwhichnewfunctionalityisobtainedbycreatinganobjectcomposedofotherobjectsThenewfunctionalityisobtainedbydelegatingfunctionalitytooneoftheobjectsbeingcomposedSometimescalledaggregationorcontainment,althoughsomeauthorsgivespecialmeaningstothesetermsCompositioncanbe:Byreference(C++)Byvalue(Java)InheritancerelatedPrinciplesForexample:Aggregationwhenoneobjectownsorisresponsibleforanotherobjectandbothobjectshaveidenticallifetimes(GoF)whenoneobjecthasacollectionofobjectsthatcanexistontheirown(UML)Containmentaspecialkindofcompositioninwhichthecontainedobjectishiddenfromotherobjectsandaccesstothecontainedobjectisonlyviathecontainerobject(Coad)InheritancerelatedPrinciplesAdvantagesOfCompositionContainedobjectsareaccessedbythecontainingclasssolelythroughtheirinterfaces"Black-box"reuse,sinceinternaldetailsofcontainedobjectsarenotvisibleGoodencapsulationFewerimplementationdependenciesEachclassisfocusedonjustonetaskThecompositioncanbedefineddynamicallyatrun-timethroughobjectsacquiringreferencestootherobjectsofthesametypeDisadvantagesOfCompositionResultingsystemstendtohavemoreobjectsInterfacesmustbecarefullydefinedinordertousemanydifferentobjectsascompositionblocksInheritancerelatedPrinciplesInheritance/CompositionSummaryBothcompositionandinheritanceareimportantmethodsofreuseInheritancewasoverusedintheearlydaysofOOdevelopmentOvertimewe'velearnedthatdesignscanbemademorereusableandsimplerbyfavoringcompositionOfcourse,theavailablesetofcomposableclassescanbeenlargedusinginheritanceSocompositionandinheritanceworktogetherButourfundamentalprincipleis:FavorCompositionOverInheritanceInheritancerelatedPrinciples要盡量使用合成、聚合,盡量不要使用繼承。合成、聚合復(fù)用原則:在新對象里面使用已有對象,使之成為新對象的一部份,新對象通過向這些對象的委派達(dá)到復(fù)用已有功能的目的。合成、聚合有如下好處:新對象存取成分對象的唯一方法是通過成分對象的接口。這種復(fù)用是黑箱復(fù)用,因?yàn)槌煞謱ο蟮膬?nèi)部細(xì)節(jié)是新對象所看不到的。這種復(fù)用可以在運(yùn)行時(shí)間內(nèi)動(dòng)態(tài)進(jìn)行,新對象可以動(dòng)態(tài)的引用與成分對象類型相同的對象。合成、聚合可以應(yīng)用到任何環(huán)境中去,而繼承只能應(yīng)用到一些有限環(huán)境中去導(dǎo)致錯(cuò)誤的使用合成、聚合與繼承的常見原因把“Has-a”關(guān)系當(dāng)作“Is-a”關(guān)系。如果兩個(gè)類是“Has-a”關(guān)系那么應(yīng)使用合成、聚合,如果是“Is-a”關(guān)系那么可使用繼承。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有些需求易于變化,前面的大設(shè)計(jì)(BigDesignUpFront)浪費(fèi)時(shí)間Overlycomplicatedand/orgoldplatingJustEnoughDesignUpFront(JEDUF)適可而止,防止設(shè)計(jì)臃腫別杞人憂天OtherUsefulDesignPrinciplesYAGNIYouAin’tGonnaNeedItXPversionofYagniis:Alwaysimplementthingswhenyouactuallyneedthem,neverwhenyoujustforeseethatyouneedthemComparedwithJEDUF?優(yōu)勢WithoutfutureproofingOtherUsefulDesignPrinciplesDRYTheDRY(Don'tRepeatYourself)Principle,alsoknownas“SinglePointControl”or“SingleSourceofTruth”,itstates:Everypieceofknowledgemusthaveasingle,unambiguous,authoritativerepresentationwithinasystem.reducingrepetitionofinformationofallkinds實(shí)現(xiàn)機(jī)制:Lotsoflittlepieces:“Goodcodeinvariablyhassmallmethodsandsmallobjects.Onlybyfactoringthesystemintomanysmallpiecesofstateandfunctioncanyouhopetosatisfythe‘onceandonlyonce’rule(OOO).”“Inaprogramwrittenwithgoodstyle,everythingissaidonceandonlyonce.”Divideprogramintomethodsthatperformoneidentifiabletask.Keepalloftheoperationsinamethodatthesamelevelofabstraction.Thiswillnaturallyresultinprogramswithmanysmallmethods,eachafewlineslong.優(yōu)勢:增加可維護(hù)性和可測試性重構(gòu):提?。ǔ╊悺⒎椒▽?shí)際上是軟件工程基本原理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)總結(jié)SRPTheSingleResponsibilityPrinciple單一責(zé)任原則

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.即要實(shí)現(xiàn)表示與業(yè)務(wù)分離ThechallengewithSRPisgettingthegranularityofaresponsibilityright.責(zé)任的定義:即類變化的理由此責(zé)任與RDD中的責(zé)任有何不同?TheSingleResponsibilityPrincipleSimpleisbeautiful.把復(fù)雜事情簡單化是智慧!Eachclassshouldhaveonlyoneresponsibilityandfocustodoonesinglething.一個(gè)類承擔(dān)的職責(zé)過多,這些職責(zé)就耦合。這時(shí)一個(gè)職責(zé)的變化可能會削弱或者抑制該類完成其它職責(zé)的能力。這種耦合導(dǎo)致脆弱設(shè)計(jì),當(dāng)變化發(fā)生時(shí),設(shè)計(jì)會遭受到難以預(yù)料的破壞Well,thisclearlyconformswithGRASPprincipleofHighCohesion.HighCohesionisanevaluativepatternthatattemptstokeepobjectsappropriatelyfocused,manageableandunderstandableSRPwouldpromotethereuseofcode,clarityandreadability.Yoursystemwouldalsobeeasiertotest,enhanceandmaintained.Developerswouldalsofindlesscontentionforsourcecodefiles.TheSingleResponsibilityPrinciple思考題:此處的責(zé)任與責(zé)任驅(qū)動(dòng)的責(zé)任在語義上是否一致?TheInterfaceSegregationPrincipleInterfacesAdvantages:ClientsareunawareofthespecificclassoftheobjecttheyareusingOneobjectcanbeeasilyreplacedbyanotherLoosenscouplingObjectconnectionsneednotbehardwiredtoanobjectofaspecificclass,therebyincreasingflexibilityIncreaseslikelihoodofreuseImprovesopportunitiesforcompositionsincecontainedobjectscanbeofanyclassthatimplementsaspecificinterfaceDisadvantages:ModestincreaseindesigncomplexityTheInterfaceSegregationPrinciple接口:java中的抽象類和interface類型。

InterfacesAninterfaceisthesetofmethodsoneobjectknowsitcaninvokeonanotherobjectAnobjectcanhavemanyinterfaces.(Essentially,aninterfaceisasubsetofallthemethodsthatanobjectimplements).AtypeisaspecificinterfaceofanobjectDifferentobjectscanhavethesametypeandthesameobjectcanhavemanydifferenttypesAnobjectisknownbyotherobjectsonlythroughitsinterfaceInasense,interfacesexpress"isakindof"inaverylimitedwayas"isakindofthatsupportsthisinterface“增加系統(tǒng)的靈活性,減少了代碼量。Interfacesarethekeytopluggability!TheInterfaceSegregationPrincipleInterfaceInheritancevsImplementationInheritanceInterfaceInheritance(Subtyping)-describeswhenoneobjectcanbeusedinplaceofanotherobjectImplementationInheritance(ClassInheritance)-anobject'simplementationisdefinedintermsofanother'sobjectsimplementationTheC++inheritancemechanismmeansbothclassandinterfaceinheritanceC++canperforminterfaceinheritancebyinheritingfromapureabstractclassJavahasaseparatelanguageconstructforinterfaceinheritance-theJavainterfaceJava'sinterfaceconstructmakesiteasiertoexpressandimplementdesignsthatfocusonobjectinterfacesTheInterfaceSegregationPrincipleClientsshouldnotbeforcedtoimplementinterfacestheydon’tuse.即類對其他類的依賴應(yīng)當(dāng)建立在最小接口上。Thedependencyofoneclasstoanotheroneshoulddependonthesmallestpossibleinterface.規(guī)避通用的涵蓋多個(gè)業(yè)務(wù)方法的接口,而用與特定客戶類有關(guān)的小接口Insteadofonefatinterfacemanysmallinterfacesarepreferredbasedongroupsofmethods,eachoneservingonesub-module.TheInterfaceSegregationPrinciple不能強(qiáng)迫用戶去依賴那些他們不使用的接口。如果用戶被迫依賴他們不用的接口,當(dāng)接口發(fā)生改變時(shí),他們也不得不跟著改變。用戶依賴了自己未用但被其他用戶用的接口,當(dāng)其他用戶修改該接口時(shí),依賴該接口的所有用戶都將受到影響。違反了開閉原則。使用多個(gè)專門的接口比使用單一的總接口總要好。它包含了2層意思:接口設(shè)計(jì)原則:應(yīng)遵循最小接口原則,不要把用戶不使用的方法塞進(jìn)同一個(gè)接口里。如果一個(gè)接口的方法沒有被使用到,則說明該接口過胖,應(yīng)該將其分割成幾個(gè)功能專一的接口。接口依賴(繼承)原則:如果一個(gè)接口a依賴(繼承)另一個(gè)接口b,則接口a相當(dāng)于繼承了接口b的方法,那么繼承了接口b后的接口a也應(yīng)該遵循上述原則:不應(yīng)該包含用戶不使用的方法。反之,則說明接口a被b給污染了,應(yīng)該重新設(shè)計(jì)它們的關(guān)系。TheInterfaceSegregationPrinciple一個(gè)類對另一個(gè)類的依賴應(yīng)該限制在最小化接口上clientshouldnotbeforcedtodependuponinterfacesthattheydon'tuse.接口級別的高內(nèi)聚(高于類級別)分離關(guān)注(SeparationofConcerns)的特例每個(gè)接口處理一個(gè)具體行為,內(nèi)聚分離接口有2種方法委托,多重繼承實(shí)施技術(shù)(有時(shí)也稱為Principle)Programtoaninterface,notanimplementationDependoninterfaces,notconcreteclassesTheInterfaceSegregationPrinciple不應(yīng)該強(qiáng)迫客戶程序依賴于它們不用的方法。接口屬于客戶,不屬于它所在的類層次結(jié)構(gòu)。Martinalsomentionsthat"fatinterfaces"—interfaceswithadditionaluselessmethods—leadtoinadvertentcouplingbetweenclasses.ThisistherealreasonwhytheSIPshouldbeadheredto.詳細(xì)說明:分離客戶就是分離接口接口隔離原則是用來處理胖接口所具有的缺點(diǎn)。如果類接口不是內(nèi)聚的,就表示該類的接口是胖的,需要減肥.減肥的原則是接口分成多組方法,每組方法都服務(wù)于特定客戶程序客戶程序調(diào)用多個(gè)具有內(nèi)聚接口的抽象基類.

TheInterfaceSegregationPrincipleOpen-ClosedPrincipleModulesthatconformtotheOCPmeettwocriteria:OpenForExtension-ThebehaviorofthemodulecanbeextendedtomeetnewrequirementsClosedForModification-theexistingsourcecodeofthemoduleisnotallowedtochangeHowcanwedothis?AbstractionPolymorphismInheritanceInterfaces增加新需求時(shí),可避免rigidity,fragilityandimmobilityOpen-ClosedPrincipleItisnotpossibletohaveallthemodulesofasoftwaresystemsatisfytheOCP,butweshouldattempttominimizethenumberofmodulesthatdonotsatisfyitTheOpen-ClosedPrincipleisreallytheheartofOOdesignConformancetothisprincipleyieldsthegreatestlevelofreusabilityandmaintainability(擴(kuò)展性和適應(yīng)性)AcorollarytotheOCPistheSingleChoicePrincipleWheneverasoftwaresystemmustsupportasetofalternatives,ideallyonlyoneclassinthesystemknowstheentiresetofalternativesTheLiskovSubstitutionPrincipleBelongtoSolidprincipleAlsoknownas“Designbycontract”AsubclassshouldhonorthecontractmadebyitparentclassesWhatiswantedhereissomethinglikethefollowingsubstitutionproperty(1988):Ifforeachobjecto1oftypeSthereisanobjecto2oftypeTsuchthatforallprogramsPdefinedintermsofT,thebehavioro

溫馨提示

  • 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. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論