華師大面向?qū)ο蟪绦蛟O(shè)計-Lec12_設(shè)計類圖及順序圖等1_第1頁
華師大面向?qū)ο蟪绦蛟O(shè)計-Lec12_設(shè)計類圖及順序圖等1_第2頁
華師大面向?qū)ο蟪绦蛟O(shè)計-Lec12_設(shè)計類圖及順序圖等1_第3頁
華師大面向?qū)ο蟪绦蛟O(shè)計-Lec12_設(shè)計類圖及順序圖等1_第4頁
華師大面向?qū)ο蟪绦蛟O(shè)計-Lec12_設(shè)計類圖及順序圖等1_第5頁
已閱讀5頁,還剩93頁未讀, 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

1、Object oriented Analysis &Design面向?qū)ο蠓治雠c設(shè)計Lecture_08 GRASP主講: 陳小紅 2Artifact InfluencesDesign 3DesignSupplementary SpecsGlossary Data dictionaryUse Case under development, with System Sequence Diagram (System operations) and ContractsConceptual Model Interactions, class diagram, etcPackagesHow?OOD

2、 nAfter identifying your requirements and creating a domain model, nthen add methods to the appropriate classes, and define the messaging between the objects to fulfill the requirements 4Requirement? requirementUse case/SSDSytemEvent/OCSystemEvent/OCUse case/SSDUse case/SSDSystemEvent/OC5?nOO System

3、 n- objects collaborating to respond to System Events6: SalemakePayment(cashTendered): Paymentcreate(cashTendered)abstract, implies Sale objects have a responsibility to create PaymentsSystemSystem EventnHow to judge whether it is finished or not? nOperation Contract nInput /Output 7How to assign?nI

4、n the process Refer to domain model to assign task to objects and make them collaborating with each other 8nHow to evaluate whether it is a good design?nHigh cohesion nLow coupling 9Back to OODRealisation ways nThe problem isnAbove advice is too general to be handlednDeciding what methods belong to

5、where and how objects should interact carries consequences and should be undertaken seriously nresponsibility-driven design (RDD)n thinking about how to assign responsibilities to collaborating objects 10Ch16. ResponsibilitiesnResponsibilities are an abstractionnSoftware objects do not have responsi

6、bilities, they have methods.nThe responsibility for persistencenLarge-grained responsibilitynThe responsibility for tax calculationnMore fine-grained responsibilitynConcretely, implemented with classes, their methods and in terms of how they collaborate with other objects.nResponsibilities are a use

7、ful metaphor11Responsibility-Driven Design (RDD)nIn RDD when designing objects we ask questions likenWhat are the responsibilities of this object?nWhat does it collaborate with? 12Basic Principles of Object Design - GRASP PrinciplesnWhat are the guiding principles to help assign responsibilities?nTh

8、ese principles are captured in the GRASP patternsnGeneral Responsibility Assignment Software PatternsnVery basic and broad principles of object design1314Basic ResponsibilitiesnThese responsibilities are of the following two types: doing and knowing nDoing (行為職責(zé))nDo it yourselfnsuch as creating an o

9、bject or doing a calculation ninitiating action in other objects ncontrolling and coordinating activities in other objects nKnowing(認知職責(zé))nknowing about private encapsulated data nknowing about related objects nknowing about things it can derive or calculate 15Basic ResponsibilitiesnResponsibilities

10、are assigned to classes of objects during object design. nFor example, we may declare that na Sale is responsible for creating SalesLineltems (a doing), or n“a Sale is responsible for knowing its total (a knowing). nRelevant responsibilities related to knowing are often inferable from the domain mod

11、el, because of the attributes and associations it illustrates.nThe translation of responsibilities into classes and methods is influenced by the granularity of the responsibility. nE.g. The responsibility n“to provide access to relational databases nmay involve dozens of classes and hundreds of meth

12、ods, packaged in a subsystem. nBy contrast, the responsibility “to create a Sale may involve only one or a few methods.16Methods Implement ResponsibilitiesnOO System n- objects collaborating to respond to System EventsnResponsibilities are often considered during the creation of interaction diagrams

13、. nNext Figure indicates that Sale objects have been given a responsibility to create Payments, which is invoked with a makePayment message and handled with a corresponding makePayment method17Methods Implement Responsibilities: SalemakePayment(cashTendered): Paymentcreate(cashTendered)abstract, imp

14、lies Sale objects have a responsibility to create PaymentsSystemSystem Event18Ch17. GRASP Designing Objects with ResponsibilitiesnHow?nApply Patterns and principles of responsibility assignmentsnGoF (Gang of Four patterns)nFamous 23 patternsn GRASP (General responsibility assignment Software pattern

15、)nA set of (9) principlesnOthersnOCP, Design Patterns Explained A New Perspective on Object-Oriented Design Second EditionBy AlanShalloway, JamesR.Trott19Experiencedobject-orienteddevelopers(andothersoftwaredevelopers)builduparepertoireofbothgeneralprinciplesandidiomaticsolutionsthatguidetheminthecr

16、eationofsoftware.Theseprinciplesandidioms,ifcodifiedinastructuredformatdescribingtheproblemandsolution,andgivenaname,maybecalledpatterns.Forexample,hereisasamplepattern:PatternsPattern Name: Information Expert Problem It Solves: What is a basic principle by which to assign responsibilities to object

17、s? Solution: Assign a responsibility to the class that has the information needed to fulfill it.20Inobjecttechnology,apatternisanameddescriptionofaproblemandsolutionthatcanbeappliedtonewcontexts;ideally,itprovidesadviceinhowtoapplyitinvaryingcircumstances,andconsiderstheforcesandtrade-offs.Manypatte

18、rnsprovideguidanceforhowresponsibilitiesshouldbeassignedtoobjects,givenaspecificcategoryofproblem.Mostsimply,apatternisanamedproblem/solutionpairthatcanbeappliedinnewcontexts,withadviceonhowtoapplyitinnovelsituationsanddiscussionofitstrade-offs.PatternsAlexander, C., The Timeless Way of Building建筑的永

19、恒之道 , New York: Oxford University Press, 1979 It is important to realize that the Gang of Four did not CREATE the patterns described in the book. Rather, they IDENTIFIED patterns that already existed within the software community, patterns that reflected what had been learned about high-quality desi

20、gns for specific problems 21GRASP PatternsnGRASPnGeneral Responsibility Assignment Software PatternsnUnderstanding and being able to apply the ideas behind GRASP while coding or while drawing interaction and class diagrams enables developers new to object technology needs to master these basic princ

21、iples as quickly as possible; they form a foundation for designing OO systems(對象技術(shù)初學(xué)者在編碼或繪制交互圖和類圖時,應(yīng)該理解并應(yīng)用GRASP的基本思想,以便盡快地掌握這些基本原則,它們是設(shè)計OO系統(tǒng)的基礎(chǔ)) nThe GRASP patterns are a learning aid to help one understand essential object design, and apply design reasoning in a methodical, rational, explainable wa

22、ys.22GRASPpatternsdescribefundamentalprinciplesofobjectdesignandresponsibilityassignment.ThefollowingisalistofGRASPpatterns:InformationExpertCreatorHighCohesionLowCouplingControllerPolymorphismIndirectionPureFabricationProtectedVariationsGRASP Patterns23Mini Exercise 1nWho will create Square object

23、in Monopoly ? Why?nThinking stepsnHave no design model, so start with Domain ModelnLRG: Low representational gap build design model (dynamic and static)Figure 17.3. Monopoly iteration-1 domain model24GRASP rule1: Creator (創(chuàng)建者)nName: CreatornProblem:n Who should be responsible for creating a new inst

24、ance of some class?nSolution: nAssign class B the responsibility to create an instance of class A if one of these is true (the more the better) :n1. B “contains” or compositely aggregates An2. B records An3. B closely uses An4. B has the initializing data for A that will be passed to A when it is cr

25、eated (B is an expert w.r.t. A)如果有一個以上的選項適用,通常首選 聚集 或包含A的類nNote:nB and A refer to software objects, not domain model objects 25Creator : example MonopolynBoard create SquarenBecause of Board contains SquareWho create Board?26Considerthepartialdomainmodel:InthePOSapplication,whoshouldberesponsiblefor

26、creatingaSalesLineltem instance?ByCreator,weshouldlookforaclassthataggregates,contains,andsoon,SalesLineltem instances.Creator : POS example27Since a Sale contains (in fact, aggregates) many SalesLineltem objects, the Creator pattern suggests that Sale is a good candidate to have the responsibility

27、of creating SalesLineltem instances.This leads to a design of object interactions as shown :Creator : POS exampleFigure 17-1328Creator When Not to UsenWhen want to reuse existing instances for performance purposes (caching)nconditionally creating an instance from one of a family of similar classes b

28、ased upon some external property value nGOF patternnDelegate responsibility further downnOther more complex situations29Creator BenefitsnExisting associations means created class is in any case visible to creatornHigh cohesionnDoes not increase coupling30Mini Exercise 2 nGiven a key, which object ca

29、n tell me aboutnSquare in MonopolynTotal money of a sale in POSnNote:nthis is a knowing responsibility 31GRASP rule2: Information ExpertnName: Information Expert(信息專家)nProblem: nWhat is a general principle of assigning responsibility to objects?nSolution: nAssign responsibility to the class that has

30、 the information necessary to fulfill responsibility32Information Expert ”Real World” Analogyn“Do It Myself” Coad or “Animation” Larman principle n objects are “alive” and can do things themselvesn“雞鳴狗盜雞鳴狗盜”nUltimate knowledge may require co-operation33Information ExpertnInformationnan objects own s

31、tate,nabout other objects, the world around an object,n information the object can derive, nand so forth nAnswer to Mini exercise 2Figure 17.6. Applying Expert 34Information Expert How to?n1. Clearly state the responsibilityn2. Look in Design Model for relevant classesn3. Else look in Domain Model a

32、nd create design classes35Information Expert Sale Total ExamplenWho should know the grand total (總計) of a sale?nProduct has information about Price so it is expert for that (getPrice method)nSalesLineItems has information about Product and Quantity so it is expert for PriceTotal (getPriceTotal metho

33、d)nSale has information SalesLineItems with associated PriceTotal so it is expert for SaleTotal (getSaleTotal method)SaledatetimeSalesLineItemquantityProductSpecificationdescriptionpriceUPCDescribed-by*Contains1.*Total = pricei *qtyiTell me the total money?36Information Expert Sale Total getSubTotal

34、 = getPriceTotalFigure 17.17. Calculating the Sale total getTotal = getSaleTotal37Information Expert Sale TotalHence responsibilities assign to the 3 classes. ClassResponsibilitySaleknows sale totalSalesLineItemknows line item subtotalProductSpecificationknows product price38Partial Information Expe

35、rtnFulfilling responsibility may require information spread across different classesnPartial information experts collaborate in taskn getSaleTotal examplenInteract through messages (methods) to share the work39Information Expert Benefits nEncapsulation n objects support their own information n suppo

36、rts low couplingnBehavior is distributed across classes n supports high cohesionContraindications: Database?40Mini-Exercise 3nWho creates the Payment?nmakePayment method invoked in RegisternA Payment has to be associated with the SalenWho creates the Payment instance?nBy creator Register, Sale are c

37、andidatesPaymentRegisterSale41Mini-Exercise 3nSolution 1nSolution 1 JustificationnRegister records PaymentnCreator patternnaddPayment method passes p instance of Payment as parameternRegister coupled to Payment class42Mini-Exercise 3nSolution 243GRASP rule3: Low Coupling (!)nName: Low CouplingnProbl

38、em: nHow to support low dependency, low change impact and increased reuse?nSolution: nAssign responsibility so coupling remains low. nUse this principle to evaluate alternativesnAll other things being equal prefer the low coupling solutionnNote: Information Expert encourages Low CouplingnWhy most se

39、cret service (spy) is one-way contact? 為什么特務(wù)工作都是為什么特務(wù)工作都是單線聯(lián)系?單線聯(lián)系?44ItcantbeconsideredinisolationfromotherpatternssuchasExpertandHighCohesion,butratherneedstobeincludedasoneofseveraldesignprinciplesthatinfluenceachoiceinassigningaresponsibility.Relation with the other patterns45CouplingnMeasure of

40、how strongly one element is:n1. connected ton2. has knowledge ofn3. relies onanother element(耦合:一個元素與其它元素的聯(lián)接、感知以及依賴的程度的度量)Cohesion,內(nèi)聚:模塊內(nèi)的操作之間聯(lián)系緊密的程度Coupling,耦合:兩個子模塊之間聯(lián)系的強度What is coupling? n(ForExample,inJava),ncommonformsofcouplingfromXtoYinclude:XhasanattributethatreferstoY.XcallsonservicesofY.X

41、hasamethodthatreferencesY(parameter,localvariable,orreturnvalue).XisadirectorindirectsubclassofY.Yisaninterface,andXimplementsthatinterface.4647CouplingnProblems with High CouplingnForced local changes because of changes in related classnIf there is coupling or dependency, then when the depended-upo

42、n element changes, the dependant may be affected.nHarder to understand in isolationnHarder to reuse drags in more classesHigh Coupling Asubclassisstronglycoupledtoitssuperclass.Thedecisiontoderivefromasuperclassneedstobecarefullyconsideredsinceitissuchastrongformofcoupling.4849Low Coupling isaprinci

43、pletokeepinmindduringalldesigndecisions;itisanunderlyinggoaltocontinuallyconsider.Itisanevaluativeprinciplethatadesignerapplieswhileevaluatingalldesigndecisions.Importance 50Thereisnoabsolutemeasureofwhencouplingistoohigh.Whatisimportantisthatadevelopercangauge(評估)thecurrentdegreeofcoupling,andasses

44、sifincreasingitwillleadtoproblems.Ingeneral,classesthatareinherentlyverygenericinnature,andwithahighprobabilityforreuse,shouldhaveespeciallylowcoupling.How to Evaluate Low Coupling51Low Coupling-To What DegreenThe extreme case of Low Coupling is when there is no coupling between classes. nThis is no

45、t desirablenbecause a central metaphor of object technology is a system of connected objects that communicate via messagesnToo little coupling means we arent a “collaborating community of objects”nit yields a poor design nbecause it leads to a few incohesive, bloated, and complex active objects that

46、 do all the work, with many very passive zero-coupled objects that act as simple data repositories.nSome moderate degree of coupling between classes is normal and necessary nto create an object-oriented system in which tasks are fulfilled by a collaboration between connected objects52Low Coupling Wh

47、en Not TonHigh coupling to stable elements and to pervasive elements is seldom a problem.ne.g. language librariesn For example, a Java J2EE application can safely couple itself to the Java libraries (java.util, and so on)n because they are stable and widespread.nLow Coupling BenefitsnNot affected by

48、 changes in other componentsnSimple to understand in isolationnConvenient to reuse53Example : Low CouplingnWhy not assign getSquare to Dog (i.e., some arbitrary other class)? nMinimal coupling will reduce change (dependency) 54Mini Exercise 4nFor Monopoly game, Which object starts the game?nUndersta

49、nding the ProblemnSSD boundary between the User and SUD (system under development)nUI layer “catches” the requestnThe request is a system operation public interfacenModel-View Separation principle says UI must not contain business logicnProblem: to which domain layer object should the UI pass the sy

50、stem operation ?55nFigure 17.8. SSD for the Monopoly game. nNote the playGame operation Play game56nAssign responsibility to receive the system operations by an object whichnRepresenting System/subsystem/device ornHandling just this use case57GRASP rule4: ControllernName: ControllernProblem: nWhat f

51、irst object beyond the UI layer receives and co-ordinates (controls) a system operationnSolution: nAssign the responsibility to a class representing one of the following choices:n1. Facade(外觀) Controller :nrepresents the overall system, a root object, a device that the object is running within, or a

52、 major sub-systemn2. Use Case or Session Controller :n represents a use case scenario within which the system event occurs58Mini Exercise 4 SolutionnThe use case that the playGame system operation occurs within is called Monopoly Game. nThus, a software class such as PlayMonopolyGameHandler 59Contro

53、ller NextGen POS ExamplenFigure 17.20. Some system operations of the NextGen POS application Conceptual representation what is the class that handles these operations?60Figure 17.21. What object should be the Controller for enterItem? 61Controller Example for POSn(Solution) optionsnFacade: Register,

54、 POSSystemnSession: ProcessSaleHandler, ProcessSaleSessionFigure 17.22. Controller choices 62Figure 17.23. Allocation of system operations 63Controller ObservationsnDelegation patternnExternal input events may come from human actors or other systemsnFacade the “face” of the domain layer to the world

55、nEx: RegisternHandler deals with a clear cut part of the issue事物一個明確的組成部分nEx: ProcessSaleNote : Session conversation where information needs to be retained between steps64Controller FacadenFacade外觀模式:nProvide a consistent interface for a set of interfaces in subsystem為子系統(tǒng)中的一組接口提供一個一致的界面n“cover” over

56、 the other layers of the applicationnAbstraction of an overall physical unit n Register, PizzaShopnThe entire software systemn POSSystemnAbstraction of some other overall system or sub-system concept n MonopolyGamenSuitable forn relatively small systems nand/or system with limited number of system o

57、perationsnin message handling system when cant direct messages to alternative controllers n Internet application servers65Session Controller Use CasenPure Fabrication n ProcessSaleHandler is not a domain concept in Domain ModelnWhen assigning to facade may lead to high coupling or low cohesion (“Blo

58、at”)nMany system operations across different processesnConceptually easier to understand and buildnSession Controllers Naming conventions: n Handler orn CoOrdinator or nSessionnUse same controller class for all system operations in the use case scenarionSession is a type of conversation between the

59、actor and the SUD66Controller vs. UInUI should not have responsibility for fulfilling system operationsnSystem operations handled in domain layern本書把 應(yīng)用邏輯層 又稱為 架構(gòu)的 領(lǐng)域?qū)樱╮ef ch13.6) nController is responsible for forwarding messages.67Controller BenefitsnAllows for easy change of UI and/or alternative

60、 UI nAllows for reuse of domain layer code (UI is usually application specific)nHelps ensure sequence of operation which may differ from UI inputnCan reason about system state UI does not preserve state68Bloated(臃腫的) Controllers The ProblemnLow cohesion unfocused and handling too many areas of responsib

溫馨提示

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

最新文檔

評論

0/150

提交評論