![华师大面向对象程序设计Lec12_设计类图及顺序图等1_第1页](http://file2.renrendoc.com/fileroot_temp3/2021-11/5/e2dcab3d-2b93-446d-b21d-58d01bea93c8/e2dcab3d-2b93-446d-b21d-58d01bea93c81.gif)
![华师大面向对象程序设计Lec12_设计类图及顺序图等1_第2页](http://file2.renrendoc.com/fileroot_temp3/2021-11/5/e2dcab3d-2b93-446d-b21d-58d01bea93c8/e2dcab3d-2b93-446d-b21d-58d01bea93c82.gif)
![华师大面向对象程序设计Lec12_设计类图及顺序图等1_第3页](http://file2.renrendoc.com/fileroot_temp3/2021-11/5/e2dcab3d-2b93-446d-b21d-58d01bea93c8/e2dcab3d-2b93-446d-b21d-58d01bea93c83.gif)
![华师大面向对象程序设计Lec12_设计类图及顺序图等1_第4页](http://file2.renrendoc.com/fileroot_temp3/2021-11/5/e2dcab3d-2b93-446d-b21d-58d01bea93c8/e2dcab3d-2b93-446d-b21d-58d01bea93c84.gif)
![华师大面向对象程序设计Lec12_设计类图及顺序图等1_第5页](http://file2.renrendoc.com/fileroot_temp3/2021-11/5/e2dcab3d-2b93-446d-b21d-58d01bea93c8/e2dcab3d-2b93-446d-b21d-58d01bea93c85.gif)
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Object oriented Analysis &Design面向对象分析与设计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? 5?nOO System n- objects collaborating to respond to System Events6: SalemakePayment(cashTendered): P
3、aymentcreate(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?nIn the process Refer to domain model to assign task to objects and make them collaboratin
4、g 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 where and how objects should interact carries consequences and should be undertaken seri
5、ously nresponsibility-driven design (RDD)n thinking about how to assign responsibilities to collaborating objects 10Ch16. ResponsibilitiesnResponsibilities are an abstractionnSoftware objects do not have responsibilities, they have methods.nThe responsibility for persistencenLarge-grained responsibi
6、litynThe 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 useful metaphor11Responsibility-Driven Design (RDD)nIn RDD when designing objects we ask qu
7、estions 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?nThese principles are captured in the GRASP patternsnGeneral Responsibility Assignment Soft
8、ware PatternsnVery basic and broad principles of object design1314Basic ResponsibilitiesnThese responsibilities are of the following two types: doing and knowing nDoing (行为职责)nDo it yourselfnsuch as creating an object or doing a calculation ninitiating action in other objects ncontrolling and coordi
9、nating activities in other objects nKnowing(认知职责)nknowing about private encapsulated data nknowing about related objects nknowing about things it can derive or calculate 15Basic ResponsibilitiesnResponsibilities are assigned to classes of objects during object design. nFor example, we may declare th
10、at 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 model, because of the attributes and associations it illustrates.nThe translation of respon
11、sibilities 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 methods, packaged in a subsystem. nBy contrast, the responsibility “to create a Sale may inv
12、olve 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. nNext Figure indicates that Sale objects have been given a responsibility to create Pa
13、yments, which is invoked with a makePayment message and handled with a corresponding makePayment method17Methods Implement Responsibilities: SalemakePayment(cashTendered): Paymentcreate(cashTendered)abstract, implies Sale objects have a responsibility to create PaymentsSystemSystem Event18Ch17. GRAS
14、P Designing Objects with ResponsibilitiesnHow?nApply Patterns and principles of responsibility assignmentsnGoF (Gang of Four patterns)nFamous 23 patternsn GRASP (General responsibility assignment Software pattern)nA set of (9) principlesnOthersnOCP, Design Patterns Explained A New Perspective on Obj
15、ect-Oriented Design Second EditionBy AlanShalloway, JamesR.Trott19Experiencedobject-orienteddevelopers(andothersoftwaredevelopers)builduparepertoireofbothgeneralprinciplesandidiomaticsolutionsthatguidetheminthecreationofsoftware.Theseprinciplesandidioms,ifcodifiedinastructuredformatdescribingtheprob
16、lemandsolution,andgivenaname,maybecalledpatterns.Forexample,hereisasamplepattern:PatternsPattern Name: Information Expert Problem It Solves: What is a basic principle by which to assign responsibilities to objects? Solution: Assign a responsibility to the class that has the information needed to ful
17、fill it.20Inobjecttechnology,apatternisanameddescriptionofaproblemandsolutionthatcanbeappliedtonewcontexts;ideally,itprovidesadviceinhowtoapplyitinvaryingcircumstances,andconsiderstheforcesandtrade-offs.Manypatternsprovideguidanceforhowresponsibilitiesshouldbeassignedtoobjects,givenaspecificcategory
18、ofproblem.Mostsimply,apatternisanamedproblem/solutionpairthatcanbeappliedinnewcontexts,withadviceonhowtoapplyitinnovelsituationsanddiscussionofitstrade-offs.PatternsAlexander, C., The Timeless Way of Building建筑的永恒之道 , New York: Oxford University Press, 1979 It is important to realize that the Gang o
19、f 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 designs for specific problems 21GRASP PatternsnGRASPnGeneral Responsibility Assignment Softw
20、are 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 principles as quickly as possible; they form a foundation for designing OO systems(对象技术初学者在编码
21、或绘制交互图和类图时,应该理解并应用GRASP的基本思想,以便尽快地掌握这些基本原则,它们是设计OO系统的基础) nThe GRASP patterns are a learning aid to help one understand essential object design, and apply design reasoning in a methodical, rational, explainable ways.22GRASPpatternsdescribefundamentalprinciplesofobjectdesignandresponsibilityassignment
22、.ThefollowingisalistofGRASPpatterns:InformationExpertCreatorHighCohesionLowCouplingControllerPolymorphismIndirectionPureFabricationProtectedVariationsGRASP Patterns23Mini Exercise 1nWho will create Square object in Monopoly ? Why?nThinking stepsnHave no design model, so start with Domain ModelnLRG:
23、Low representational gap build design model (dynamic and static)Figure 17.3. Monopoly iteration-1 domain model24GRASP rule1: Creator (创建者)nName: CreatornProblem:n Who should be responsible for creating a new instance of some class?nSolution: nAssign class B the responsibility to create an instance o
24、f 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 created (B is an expert w.r.t. A)如果有一个以上的选项适用,通常首选 聚集 或包含A的类nNote:nB and A refer to softwa
25、re objects, not domain model objects 25Creator : example MonopolynBoard create SquarenBecause of Board contains SquareWho create Board?26Considerthepartialdomainmodel:InthePOSapplication,whoshouldberesponsibleforcreatingaSalesLineltem instance?ByCreator,weshouldlookforaclassthataggregates,contains,a
26、ndsoon,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 of creating SalesLineltem instances.This leads to a design of object interactions as sho
27、wn :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 based upon some external property value nGOF patternnDelegate responsibility further down
28、nOther 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 can tell me aboutnSquare in MonopolynTotal money of a sale in POSnNote:nthis is a knowing
29、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 the information necessary to fulfill responsibility32Information Expert ”Real World” An
30、alogyn“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 state,nabout other objects, the world around an object,n information the object can deriv
31、e, 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 and create design classes35Information Expert Sale Total ExamplenWho should know the gran
32、d 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 method)nSale has information SalesLineItems with associated PriceTotal so it is expert for Sa
33、leTotal (getSaleTotal method)SaledatetimeSalesLineItemquantityProductSpecificationdescriptionpriceUPCDescribed-by*Contains1.*Total = pricei *qtyiTell me the total money?36Information Expert Sale Total getSubTotal = getPriceTotalFigure 17.17. Calculating the Sale total getTotal = getSaleTotal37Inform
34、ation Expert Sale TotalHence responsibilities assign to the 3 classes. ClassResponsibilitySaleknows sale totalSalesLineItemknows line item subtotalProductSpecificationknows product price38Partial Information ExpertnFulfilling responsibility may require information spread across different classesnPar
35、tial information experts collaborate in taskn getSaleTotal examplenInteract through messages (methods) to share the work39Information Expert Benefits nEncapsulation n objects support their own information n supports low couplingnBehavior is distributed across classes n supports high cohesionContrain
36、dications: 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 candidatesPaymentRegisterSale41Mini-Exercise 3nSolution 1nSolution 1 JustificationnRegist
37、er records PaymentnCreator patternnaddPayment method passes p instance of Payment as parameternRegister coupled to Payment class42Mini-Exercise 3nSolution 243GRASP rule3: Low Coupling (!)nName: Low CouplingnProblem: nHow to support low dependency, low change impact and increased reuse?nSolution: nAs
38、sign 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 secret service (spy) is one-way contact? 为什么特务工作都是单为什么特务工作都是单线联系?线联系?44Itcantbeconsideredi
39、nisolationfromotherpatternssuchasExpertandHighCohesion,butratherneedstobeincludedasoneofseveraldesignprinciplesthatinfluenceachoiceinassigningaresponsibility.Relation with the other patterns45CouplingnMeasure of how strongly one element is:n1. connected ton2. has knowledge ofn3. relies onanother ele
40、ment(耦合:一个元素与其它元素的联接、感知以及依赖的程度的度量)Cohesion,内聚:模块内的操作之间联系紧密的程度Coupling,耦合:两个子模块之间联系的强度What is coupling? n(ForExample,inJava),ncommonformsofcouplingfromXtoYinclude:XhasanattributethatreferstoY.XcallsonservicesofY.XhasamethodthatreferencesY(parameter,localvariable,orreturnvalue).Xisadirectorindirectsub
41、classofY.Yisaninterface,andXimplementsthatinterface.4647CouplingnProblems with High CouplingnForced local changes because of changes in related classnIf there is coupling or dependency, then when the depended-upon element changes, the dependant may be affected.nHarder to understand in isolationnHard
42、er to reuse drags in more classesHigh Coupling Asubclassisstronglycoupledtoitssuperclass.Thedecisiontoderivefromasuperclassneedstobecarefullyconsideredsinceitissuchastrongformofcoupling.4849Low Coupling isaprincipletokeepinmindduringalldesigndecisions;itisanunderlyinggoaltocontinuallyconsider.Itisan
43、evaluativeprinciplethatadesignerapplieswhileevaluatingalldesigndecisions.Importance 50Thereisnoabsolutemeasureofwhencouplingistoohigh.Whatisimportantisthatadevelopercangauge(评估)thecurrentdegreeofcoupling,andassessifincreasingitwillleadtoproblems.Ingeneral,classesthatareinherentlyverygenericinnature,
44、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 not desirablenbecause a central metaphor of object technology is a system of connected obj
45、ects 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 do all the work, with many very passive zero-coupled objects that act as simple data re
46、positories.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 When Not TonHigh coupling to stable elements and to pervasive elements is seldom a problem
47、.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 changes in other componentsnSimple to understand in isolationnConvenient to reuse53Exam
48、ple : 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?nUnderstanding the ProblemnSSD boundary between the User and SUD (system under development)nUI lay
49、er “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 system operation ?55nFigure 17.8. SSD for the Monopoly game. nNote the playGame operation P
50、lay game56nAssign responsibility to receive the system operations by an object whichnRepresenting System/subsystem/device ornHandling just this use case57GRASP rule4: ControllernName: ControllernProblem: nWhat first object beyond the UI layer receives and co-ordinates (controls) a system operationnS
51、olution: 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 major sub-systemn2. Use Case or Session Controller :n represents a use case scenario wit
52、hin 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 59Controller NextGen POS ExamplenFigure 17.20. Some system operations of the NextGen POS applicat
53、ion 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, POSSystemnSession: ProcessSaleHandler, ProcessSaleSessionFigure 17.22. Controller choice
54、s 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 worldnEx: RegisternHandler deals with a clear cut part of the issue事物一个明确的组成部分nEx: ProcessSale
55、Note : Session conversation where information needs to be retained between steps64Controller FacadenFacade外观模式:nProvide a consistent interface for a set of interfaces in subsystem为子系统中的一组接口提供一个一致的界面n“cover” over the other layers of the applicationnAbstraction of an overall physical unit n Register,
56、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 operationsnin message handling system when cant direct messages to alternative controllers
57、 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 (“Bloat”)nMany system operations across different processesnConceptually easier to understand
58、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 actor and the SUD66Controller vs. UInUI should not have responsibility for fulfilling sys
59、tem operationsnSystem operations handled in domain layern本书把 应用逻辑层 又称为 架构的 领域层(ref ch13.6) nController is responsible for forwarding messages.67Controller BenefitsnAllows for easy change of UI and/or alternative UI nAllows for reuse of domain layer code (UI is usually application specific)nHelps ens
60、ure 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 responsibility:nWhen have a facade controller handling all of many system eventsnWhen the controll
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- Unit 5 We're family (说课稿)-2024-2025学年外研版(三起)(2024)英语三年级上册
- 1《学习伴我成长》(说课稿)-部编版道德与法治三年级上册
- Unit 2 Different families Part B Let's talk(说课稿)-2024-2025学年人教PEP版(2024)英语三年级上册
- 2《用水计量时间》说课稿-2024-2025学年科学五年级上册教科版
- 2025产品购销合同样书
- 2023九年级数学下册 第25章 投影与视图25.1 投影第2课时 正投影说课稿 (新版)沪科版001
- 2025城市民用户燃气工程实施合同书范本范文
- 2025妇女发展监测评估项目工程合同管理
- 2025合同模板合伙人利润分配协议范本
- 2024-2025学年高中政治 第3单元 第6课 第1框 源远流长的中华文化说课稿 新人教版必修3001
- 2025年上半年中煤科工集团北京华宇工程限公司中层干部公开招聘易考易错模拟试题(共500题)试卷后附参考答案
- 2025年教科版新教材科学小学一年级下册教学计划(含进度表)
- 北京市海淀区2024-2025学年五年级上册语文期末试卷(有答案)
- 《亚太经合组织》课件
- 2024年高考政治必修三《政治与法治》常考材料题考点梳理汇编
- 《会展概述》课件
- 《郴州市总体规划》课件
- 完整版金属学与热处理课件
- T∕CSTM 00640-2022 烤炉用耐高温粉末涂料
- 心脑血管病的危害教学课件
- 民用机场不停航施工安全管理措施
评论
0/150
提交评论