版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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? 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 (行为职责)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(认知职责)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(对象技术初学者在编码或绘制交互图和类图时,应该理解并应用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 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 (创建者)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? 为什么特务工作都是为什么特务工作都是单线联系?单线联系?44ItcantbeconsideredinisolationfromotherpatternssuchasExpertandHighCohesion,butratherneedstobeincludedasoneofseveraldesignprinciplesthatinfluenceachoiceinassigningaresponsibility.Relation with the other patterns45CouplingnMeasure of
40、how strongly one element is:n1. connected ton2. has knowledge ofn3. relies onanother element(耦合:一个元素与其它元素的联接、感知以及依赖的程度的度量)Cohesion,内聚:模块内的操作之间联系紧密的程度Coupling,耦合:两个子模块之间联系的强度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为子系统中的一组接口提供一个一致的界面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本书把 应用逻辑层 又称为 架构的 领域层(ref 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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年南京市卫生健康委员会、南京市机关事务管理局部分事业单位公开招聘卫技人员备考题库及1套参考答案详解
- 2026年石油化工企业生产部经理选拔测试题集
- 2026年财务管理高级顾问面试题目与答案
- 2026年项目管理专业人士PMP考试备考资料与高频考点解析
- 2026年禁毒知识竞赛190题及答案
- 2026年土地登记考试题库及答案解析
- 2026年薪酬福利专员面试题集
- 2026年影视制片人面试指南与题目
- (2025)餐后低血压管理的中国专家共识课件
- (新教材)2026年冀教版三年级上册数学 3.5 升国旗仪式 课件
- 汇能控股集团校招题库及答案
- 喷塑委外合同范本
- 高二化学上学期期末试题带答案解析
- 高标准农田建设培训课件
- 解答题 概率与统计(专项训练12大题型+高分必刷)(原卷版)2026年高考数学一轮复习讲练测
- 2024-2025学年北京市海淀区第二十中学高二上学期期末物理试题(含答案)
- 送你一朵小红花评语
- 2025至2030中国IT培训行业项目调研及市场前景预测评估报告
- 2025年国家开放大学《普通心理学(研究生)》期末考试参考题库及答案解析
- 多联机空调安装施工方案
- 2025秋期版国开河南电大专科《公务员制度讲座》一平台我要考试无纸化考试试题及答案
评论
0/150
提交评论