《软件工程》Computer Science 中ppt课件_第1页
《软件工程》Computer Science 中ppt课件_第2页
《软件工程》Computer Science 中ppt课件_第3页
《软件工程》Computer Science 中ppt课件_第4页
《软件工程》Computer Science 中ppt课件_第5页
已阅读5页,还剩95页未读 继续免费阅读

下载本文档

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

文档简介

1、Object-Oriented Design Collaboration / Design DiagramsChapter 14 - Design Dynamic view, Interaction Diagrams - How objects will communicate to fulfill requirements Assign responsibilities Design patterns Static view, Design Class Diagrams - Definition of class and interfacesChapter 15 - Interaction

2、Diagrams Illustrates how objects interact via messages to fulfill tasks Prior artifacts Domain model System operation contracts Use cases Starting point - fulfillment of operation contract post-conditionsDiagram Types Two types Collaboration SequenceCollaboration Diagram:ClassAInstance:ClassBInstanc

3、e1: message2()2: message3()message1()Sequence Diagram:ClassAInstance:ClassBInstancemessage2()message1()message3()Sequence Diagram Strengths Clearly shows sequence or time ordering Weaknesses Must add new vertical line when adding new objectsCollaboration Diagram Strengths Space economical Easier to

4、illustrate complex branching, iteration, and concurrent behavior Weaknesses Difficult to see sequence of messages More complex notationExample - Collaboration1: makePayment(cashTendered)1.1: create(cashTendered): Register:Sale:PaymentmakePayment(cashTendered)creation indicated with acreate messagedi

5、rection of messagefirst messageinstancefirst internal messagelink lineparameterExample - Sequence: Register: SalemakePayment(cashTendered)makePayment(cashTendered): Paymentcreate(cashTendered)an activation box showingthe focus of controlSame as previous diagramEmphasizes “focus of controlImportant A

6、rtifact Assign responsibilities Design object collaborations Significant amount of time Use patterns - structural guidelines and principles Notation-only chapterApproach Create separate diagram for each system operation System operation is starting message If diagram gets complex greater than 8.5x11

7、 split into smaller diagramsApproach Use operation contract responsibilities / post-conditions and use case description as starting point Design system of interacting objects to fulfill tasks Apply GRASP and patterns to develop good designClass And InstancesSale:Sales1: Saleclassinstancenamed instan

8、ceInstance is underlinedClass name preceded by colonMessage Syntaxspec := getProductSpec( id )spec := getProductSpec( id : ItemID )spec := getProductSpec( id : ItemID ) : ProductSpecificationReturn := messageparameter : parameterType : returnTypeParts are optionalLinks1: makePayment(cashTendered)2:

9、foo()2.1: bar(): Register:Salelink lineConnection path between instancesInstance of an associationClient to server messageMessages1: msg2()2: msg3()3: msg4()3.1: msg5(): Register:Saleall messages flow on the same linkmsg1()Labeled arrowSequenceMessage to “self or “this: Registermsg1()1: clear()Creat

10、ion of Instance1: create(cashier): Register:Sale newcreate message, with optional initializing parameters. This willnormally be interpreted as a constructor call.create1: make(cashier): Register:Sale newif an unobvious creation message name is used, themessage may be stereotyped for clarityCreate is

11、 language independentCreate maps to C+ “new+constructorMessage Number Sequencing:ClassAmsg1():ClassB1: msg2():ClassC1.1: msg3()not numberedlegal numberingMessage Number Sequencing;ClassAmsg1():ClassB1: msg2():ClassC1.1: msg3()2.1: msg5()2: msg4():ClassD2.2: msg6()firstsecondfourthsixthfifththirdCond

12、itional Message1 color = red : calculate(): Foo: Barmessage1()conditional message, with testconditionalClause - must evaluate to TRUEMutually Exclusive1a test1 : msg2():ClassA:ClassB:ClassC1a.1: msg3()msg1():ClassD1b not test1 : msg4()1b.1: msg5():ClassE2: msg6()unconditional aftereither msg2 or msg

13、41a and 1b are mutuallyexclusive conditional pathsIteration1 * i:=1.N: num := nextInt(): SimulatorrunSimulation(): Randomiteration is indicated with a * and an optionaliteration clause following the sequence numberIteration indicated by *Sent repeatedly specified number of timesIteration over Collec

14、tion1 *: st := getSubtotal(): Salet := getTotal()double box indicates a multiobject (collection)for example, a List object containing manySalesLineItem objects*:SalesLineItem:SalesLineItemthese two * symbols used together implyiteration over the multiobject and sending thegetSubtotal message to each

15、 memberCollection - multiobjectMessage to a Classlist := synchronizedList( aList ): InstanceOfFoojava.util.Collectionsmsg1()not underlined,therefore a classmessage to class, or astatic method callStatic methodSequence Diagram - Messages: Register: Salemsg2()msg3()msg1()msg4()msg5()Focus of Control -

16、 Activation BoxMessage to “self or “this: Registermsg1()clear()Creation of Instance: Register: SalemakePayment(cashTendered): Paymentcreate(cashTendered)authorize()note that newly createdobjects are placed at theircreation heightan object lifeline shows the extent ofthe life of the object in the dia

17、gramObject Lifelines: Sale: Paymentcreate(cashTendered).the destroy stereotypedmessage, with the largeX and short lifelineindicates explicit objectdestructiondestroyXConditional Message: Bar: Foo color = red calculate()message1()Mutually Exclusive: B: A x 15 calculate()Iteration: Simulator: Random*

18、i:=1.N: num := nextInt()runSimulation()Iteration Over a Set of Messages: Simulator: Randomhours := nextInt()runSimulation(): Programmerwork( hours )* i:=1.Neat()Iteration Over Multiobject: Sale* : st := getSubtotal()t := getTotal():SalesLineItem:SalesLineItemMessage to a Class: Foolist := synchroniz

19、edList( aList )message1()java.util.Collectionsnot underlined,therefore a classmessage to class, or astatic method callChapter 16 - GRASP Patterns for assigning responsibilities Object-oriented system - objects sending messages to each other to complete operations GRASP patterns Good design principle

20、s Applied during creation of interaction diagramsResponsibility Contract or obligation of a type or class Knowing about private encapsulated data about related objects about things it can derive or calculate Doing something itself initiating action in other objects controlling and coordinating activ

21、ities in other objectsPatterns Responsibilities assigned during design Pattern - named description of problem and solution that can be applied to new context “One persons pattern is another persons primitive building block Patterns capture existing, known knowledgePatterns Patterns have names sugges

22、ts how it applies facilitates communication GRASP General Responsibility Assignment Software Pattern fundamental principles of assigning responsibilities to objectsFirst Five GRASP Patterns Expert Creator High Cohesion Low Coupling ControllerExpert Solution: Assign a responsibility to the informatio

23、n expert-the class that has the information necessary to fulfill the responsibility. Problem: What is the most basic principle by which responsibilities are assigned in object oriented design?Expert A class model may define dozens or hundreds of software classes, and an application may require hundr

24、eds or thousands of responsibilities to be fulfilled. During object-oriented design, when the interactions between objects are defined, we make choices about the assignment of responsibilities to classes. Done well, systems tend to be easier to understand, maintain, and extend, and there is an oppor

25、tunity to reuse components in future applicationsExpert Start assigning responsibilities by clearly stating the responsibility Who should be responsible for knowing the grand total of a sale? For all SaleLineItems sum their subtotalsSale Is ExpertSaledatetimeSalesLineItemquantityProductSpecification

26、descriptionpriceitemIDDescribed-by*Contains1.*11ExpertSaledatetimegetTotal():Salet := getTotal()New methodSale: Knows calculates sale totalExpertSaledatetimegetTotal()SalesLineItemquantitygetSubtotal()New method1 *: st := getSubtotal(): Salet := getTotal()*:SalesLineItem:SalesLineItemSalesLineItem:

27、Knows calculates line item subtotalExpertSaledatetimegetTotal()SalesLineItemquantitygetSubtotal()ProductSpecificationdescriptionpriceitemIDgetPrice()New method:ProductSpecification1.1: p := getPrice()1 *: st := getSubtotal(): Salet := getTotal()*:SalesLineItem:SalesLineItemProductSpecification: Know

28、s product priceExpert Class Sale SalesLineItem ProductSpecification Responsibility knows sale total knows line item subtotal knows product priceExpert Basic guiding principle Objects do things related to information they have May require “partial experts Give responsibility to object with informatio

29、n necessary to fulfill Encapsulation maintained, objects use their own informationCreator Solution: Assign class B the responsibility to create an instance of class A if one of the following is true: B aggregates A objects. B contains A objects. B records instances of A objects. B closely uses A obj

30、ects. B has the initializing data that will be passed to A when it is created thus B is an Expert with respect to creating A. Creator B is a creator of A objects. If more than one option applies, prefer a class B which aggregates or contains class A.Creator Problem: Who should be responsible for cre

31、ating a new instance of some class? The creation of objects is one of the most common activities in an object-oriented system. Consequently, it is useful to have a general principle for the assignment of creation responsibilities. Assigned well, the design can support low coupling, increased clarity

32、, encapsulation, and reusability.CreatorSaledatetimeSalesLineItemquantityProductSpecificationdescriptionpriceitemIDDescribed-by*Contains1.*11Who should be responsible for creating a SaleLineItem instance?Creator Sale contains aggregates SalesLineItem objects - Sale responsible Aggregation - whole /

33、part relationshipLow Coupling Solution: Assign a responsibility so that coupling remains low. Problem: How to support low dependency and increased reuse?Low Coupling Coupling is a measure of how strongly one class is connected to, has knowledge of, or relies upon other classes. A class with low or w

34、eak coupling is not dependent on too many other classes; too many is context dependent but will be examined.Low Coupling A class with high or strong coupling relies upon many other classes. Such classes are undesirable; they suffer from the following problems: Changes in related classes force local

35、changes. Harder to understand in isolation. Harder to reuse because its use requires the additional presence of the classes it is dependent upon.Low Coupling: Registerp : Payment:SalemakePayment()1: create()2: addPayment(p)Register: Which is preferred?Low Coupling: Register:Sale:PaymentmakePayment()

36、1: makePayment()1.1. create()Low Coupling Second preferred, Register is less dependent Low Coupling and Creator may suggest different solutions Coupling may not be important if reuse is not a goal, how important is reuse? Extreme of Low Coupling - few bloated, complex objects violates high cohesion

37、Moderate coupling is expectedHigh Cohesion Solution: Assign a responsibility so that cohesion remains high. Problem: How to keep complexity manageable?High Cohesion In terms of object-oriented design, cohesion or more specifically, functional cohesion is a measure of how strongly related and focused

38、 the responsibilities of a class are. A class with highly related responsibilities, and which does not do a tremendous amount of work, has high cohesion.High Cohesion A class with low cohesion does many unrelated things or does too much work. Such classes are undesirable; they suffer from the follow

39、ing problems: hard to comprehend hard to reuse hard to maintain delicate; constantly effected by changeHigh Cohesion Low cohesion classes often represent a very large-grain of abstraction, or have taken on responsibilities that should have been delegated to other objects.High Cohesion Must consider

40、in light of Expert / Low Coupling, strike a balance If a “person takes on too many unrelated responsibilities, person is not effective “Fine grain of related functionality supports reuseController Solution: Assign the responsibility for receiving or handling a system event message to a class represe

41、nting one of the following choices: Represents the overall system, device, or subsystem facade controller.Controller Represents a use case scenario within which the system event occurs, often named Handler, Coordinator, or Session use-case or session controller Use the same controller class for all

42、system events in the same use case scenario. Informally, a session is an instance of a conversation with an actor. Sessions can be of any length, but are often organized in terms of use cases use case sessions.Controller Corollary: Note that window, applet, application, view, and document classes ar

43、e not on this list. Such classes should not fulfill the tasks associated with system events, they typically receive these events and delegate them to a controller.Controller Problem: Who should be responsible for handling an input system event? An input system event is an event generated by an exter

44、nal actor. They are associated with system operations - operations of the system in response to system events, just as messages and methods are related.Controller For example, when a cashier using a POS terminal presses the “End Sale button, he is generating a system event indicating “the sale has e

45、nded. Similarly, when a writer using a word processor presses the “spell check button, he is generating a system event indicating “perform a spell check. A Controller is a non-user interface object responsible for receiving or handling a system event. A Controller defines the method for the system o

46、peration.ControllerWhich class of object should be responsible for receiving thissystem event message?It is sometimes called the controller or coordinator. It does notnormally do the work, but delegates it to other objects.The controller is a kind of facade onto the domain layer fromthe interface la

47、yer.actionPerformed( actionEvent ): ?: Cashier:SaleJFramepresses buttonenterItem(itemID, qty)InterfaceLayerDomainLayersystem event messageController Previously we identified “system operations, “who is responsible for them? Possible Register - overall system Store - overall business Cashier - active

48、 in real-world BuyItemsHandler - artificial handlerController Cohesion and coupling influence decision Normally, a controller should delegate to other objects the work that needs to be done; it coordinates or controls the activity. It does not do much work itself. Dont assign operations to “interfac

49、eBloated Controller Single controller for all events and there are many Controller does not delegate tasks Controller has many attributes, maintains significant information Approach Add more controllers Delegate responsibilityChapter 17 - Design Model Read this chapter! Explains design decisions The

50、re are multiple possible design solutions, design is a tradeoff between the design patterns previously discussed Not all required information will be found in existing artifactsDeveloping Interaction Diagrams Create a separate diagram for each system operation - it is starting message Using contract

51、 responsibilities / post-conditions, and use case description as a starting point, design system of interacting objects to fulfill the tasks Apply patterns to develop good design Next page more detailDeveloping Interaction Diagrams Choose the controller Separate Model from View more detail next week

52、 Creation / Association from post-conditions suggests Creator pattern State the responsibility Expert pattern - who will be responsible Do “startup last - information will be availableChapter 18 - Visibility For a sender to send a message to an object, the sender must have a reference or pointer to

53、the receiver object Visibility - ability of an object to see or have reference to another object; is one object within the scope of anotherTypes of Visibility Attribute - B is an attribute of A Parameter - B is a parameter of a method of A Locally declared - B is declared as a local object Globally

54、declared - B is declared as a global objectAttribute Visibility: RegisterenterItem(itemID, quantity): ProductCatalogspec := getSpecification( itemID )public void enterItem(itemID, qty) . spec = catalog.getSpecification(itemID) .class Register . private ProductCatalog catalog; .Persists as long as ob

55、jects existParameter Visibility2: makeLineItem(spec, qty)enterItem(id, qty)1: spec := getSpecification(id)2.1: create(spec, qty):Register:Sale:ProductCatalogsl : SalesLineItemmakeLineItem(ProductSpecification spec, int qty) . sl = new SalesLineItem(spec, qty); .Scope of method - temporaryLocal Visib

56、ility2: makeLineItem(spec, qty)enterItem(id, qty)2: spec := getSpecification(id)2.1: create(spec, qty):Register:Sale:ProductCatalogsl : SalesLineItem/ initializing method (e.g., a Java constructor)SalesLineItem(ProductSpecification spec, int qty).productSpec = spec; / parameter to attribute visibili

57、ty.Create a local variable - temporaryGlobal Visibility: RegisterenterItem(itemID, quantity): ProductCatalogspec := getSpecification( itemID )enterItem(id, qty)./ local visibility via assignment of returning objectProductSpecification spec = catalog.getSpecification(id);.Global variableSingletonChap

58、ter 19 - Design Class Diagrams Follows / Performed in parallel to creation of sequence diagrams Diagrams include: Classes Associations Attributes, type information Methods DependenciesCreation Identify all the classes participating in the software solution, do this by analyzing the interaction diagr

59、ams Draw them in a class diagram Duplicate the attributes from the associated concepts in the conceptual modelCreation Add method names by analyzing the interaction diagrams Create - language specific Acessor - get Mutator - set Add type information to the attributes and methodsCreation Add the asso

60、ciations necessary to support the required attribute visibility Add navigability arrows to the associations to indicate the direction of attribute visibility Add dependency relationship linesExampleRegisterenterItem(.)SaledateisComplete : BooleantimemakeLineItem(.)CapturesNavigability11Three section

温馨提示

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

最新文档

评论

0/150

提交评论