06-PatternsI

Embed Size (px)

Citation preview

  • 7/28/2019 06-PatternsI

    1/50

    Object Oriented Analysis and DesignDesign Patterns I

    Matthew Dailey

    Computer Science and Information ManagementAsian Institute of Technology

    Matthew Dailey (CSIM-AIT) Design Patterns I 1 / 50

    http://find/http://goback/
  • 7/28/2019 06-PatternsI

    2/50

    Readings

    Readings for these lecture notes:

    - Larman (2005), Applying UML and Patterns: An Introduction to

    Object-Oriented Analysis and Design and Iterative Development, 3rdedition, Chapter 17.

    Some material c Larman (2005).

    Matthew Dailey (CSIM-AIT) Design Patterns I 2 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    3/50

    Outline

    1 Introduction

    2 Responsibility-Driven Design

    3 Basic GRASP Patterns

    4 Wrap-Up

    Matthew Dailey (CSIM-AIT) Design Patterns I 3 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    4/50

    IntroductionGetting started with design modeling

    Object-oriented design is not about UML. It is primarily about assigningresponsibilities to objects.

    Design modeling normally begins on the first elaboration iteration. Thesituation:

    A two-day requirements workshop has been completed.

    10%20% of the requirements have been detailed.

    The large-scale architecture has been defined.

    We have use case text, system sequence diagrams, operationcontracts, and a domain model.

    We organize a one-day modeling workshop.

    Matthew Dailey (CSIM-AIT) Design Patterns I 4 / 50

    http://find/http://goback/
  • 7/28/2019 06-PatternsI

    5/50

    IntroductionDesign guidelines

    Some guidelines for the design process:

    For OOD we use the metaphor of responsibility-driven design. Weattempt to determine how responsibilities should be divvied upbetween software objects.

    During design modeling, we focus on the difficult and/or creativeparts of the design.

    We create models for communication and understanding, not for

    documentation.

    Matthew Dailey (CSIM-AIT) Design Patterns I 5 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    6/50

    IntroductionDesign outputs

    Possible outputs of the design process:

    Interaction diagrams

    Class diagramsPackage diagrams

    UI sketches

    Database design

    Report sketches

    Matthew Dailey (CSIM-AIT) Design Patterns I 6 / 50

    http://find/http://goback/
  • 7/28/2019 06-PatternsI

    7/50

    IntroductionArtifact relationships

    We will begin realizing our usecases by assigning systemoperations from SSD analysisto software objects.

    We might derive the softwareclasses from the domain modelor create new classes.

    Then we will determine howthose objects collaborate withother objects to implement thesystem operation includingoperation contractpostconditions.

    Operation:enterItem()

    Post-conditions:- . . .

    Operation Contracts

    Sale

    date. . .

    Sales

    LineItem

    quantity

    1..*1. . .

    . . .

    Domain Model

    Use-Case Model

    Design Model: Register

    enterItem

    (itemID, quantity)

    : P roductCatalog

    d =getProductDescription(itemID)

    addLineItem( d, quantity )

    : Sale

    Require-ments

    BusinessModeling

    Design

    Sample UP Artifact Relationships

    : System

    enterItem(id, quantity)

    Use Case Text

    System Sequence Diagrams

    makeNewSale()

    system

    events

    Cashier

    ProcessSale

    : Cashier

    use

    case

    names

    system

    operations

    Use Case Diagram

    SupplementarySpecification

    Glossary

    starting events todesign for, anddetailed post-condition tosatisfy

    Process Sale

    1. Customerarrives ...2. ...3. Cashierenters itemidentifier.

    inspiration fornames ofsomesoftwaredomainobjects

    functionalrequirementsthat must berealized by

    the objects

    ideas for

    the post-conditions

    Register

    ...

    makeNewSale()enterItem(...)...

    ProductCatalog

    ...

    getProductDescription(...)...

    1*

    non-functionalrequirements

    domain rules

    item details,formats,validation

    Larman (2005), Fig. 17.1

    Matthew Dailey (CSIM-AIT) Design Patterns I 7 / 50

    http://find/http://goback/
  • 7/28/2019 06-PatternsI

    8/50

    Outline

    1 Introduction

    2 Responsibility-Driven Design

    3 Basic GRASP Patterns

    4 Wrap-Up

    Matthew Dailey (CSIM-AIT) Design Patterns I 8 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    9/50

    Responsibility-Driven DesignIntroduction

    Responsibility-driven design concerns object responsibilities, roles, andcollaborations.

    There are two types of responsibilities:

    Doing responsibilities concern performing a task such as creating anobject, performing a calculation, coordinating activities, and so on.

    Knowing responsibilities concern knowing about private data, relatedobjects, data needed for calculations, and so on.

    We say that responsibilties are fulfilled by object methods.

    Matthew Dailey (CSIM-AIT) Design Patterns I 9 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    10/50

    Responsibility-Driven DesignExample: Knowing responsibilities

    Example of applying responsibility-driven design:

    Knowing responsibilities will often be inspired by the domain model.Given a domain object Sale having a time attribute, according to theprinciple of minimal representational gap, we would probably say that theSale software object should be responsible for knowing its time.

    Matthew Dailey (CSIM-AIT) Design Patterns I 10 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    11/50

    Responsibility-Driven DesignCollaborations

    Collaborations mean the objects that cooperate to get work done.

    Collaboration example: a Sale object might invoke the getSubtotal methodon multiple SaleLineItem objects to fulfill the responsibility of calculating atotal.

    Matthew Dailey (CSIM-AIT) Design Patterns I 11 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    12/50

    Responsibility-Driven DesignGRASP

    GRASP: General Responsibility Assignment Software Patterns orPrinciples.

    GRASP provides basic patterns or principles for assignment ofresponsibilities to objects.

    When drawing interaction diagrams, you are implicitly assigningresponsibilities to particular objects.

    Use GRASP when drawing interaction diagrams and coding.

    Matthew Dailey (CSIM-AIT) Design Patterns I 12 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    13/50

    Responsibility-Driven DesignFundamental GRASP principles

    5 fundamental GRASP principles/patterns:

    Creator: who should be responsible for creating a specific object?

    Information Expert: who should be responsible for knowing about aparticular object?

    Low Coupling: how strongly should elements be tied to others?

    Controller: who should be the first to receive a message in thedomain layer?

    High Cohesion: how should responsibilities be grouped within classes?

    Matthew Dailey (CSIM-AIT) Design Patterns I 13 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    14/50

    Outline

    1 Introduction

    2 Responsibility-Driven Design

    3 Basic GRASP Patterns

    4 Wrap-Up

    Matthew Dailey (CSIM-AIT) Design Patterns I 14 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    15/50

    Basic GRASP PatternsCreator pattern

    The Creator pattern: who should be responsible for creating instancesof class A?

    B creates A if:B contains A

    B records A

    B closely uses A

    B has the information needed to create A

    Matthew Dailey (CSIM-AIT) Design Patterns I 15 / 50

    http://find/
  • 7/28/2019 06-PatternsI

    16/50

    Basic GRASP PatternsCreator principle

    Example: in Monopoly, who should create the Square objects?

    First, consider the domain model:

    Larman (2005), Fig. 17.3

    Matthew Dailey (CSIM-AIT) Design Patterns I 16 / 50

    B i GRASP P

    http://find/
  • 7/28/2019 06-PatternsI

    17/50

    Basic GRASP PatternsCreator principle

    The Board object contains Square objects, so it is a good candidate.

    Larman (2005), Fig. 17.4

    This gives us a clue that the relationship should be a composition:

    Larman (2005), Fig. 17.5

    Matthew Dailey (CSIM-AIT) Design Patterns I 17 / 50

    B i GRASP P

    http://find/http://goback/
  • 7/28/2019 06-PatternsI

    18/50

    Basic GRASP PatternsCreator principle

    Example: in the POS system, who should create the SalesLineItemobjects?

    First, consider the domain model:

    Sale

    time

    Sales

    LineItem

    quantity

    ProductDescription

    descriptionpriceitemID

    Described-by*

    Contains

    1..*

    1

    1

    Larman (2005), Fig. 17.12

    Matthew Dailey (CSIM-AIT) Design Patterns I 18 / 50

    B i GRASP P

    http://find/http://goback/
  • 7/28/2019 06-PatternsI

    19/50

    Basic GRASP PatternsCreator principle

    We see that Sale contains SalesLineItem, so we give the responsibility to

    Sale in the dynamic model:

    : Register : Sale

    makeLineItem(quantity)

    : SalesLineItemcreate(quantity)

    Larman (2005), Fig. 17.13

    When object creation is sufficiently complex, involving recycling,polymorphism, and so on, it may be useful to separate the creationresponsibility into a Factory helper class (GoF, Larman Ch. 26).

    Matthew Dailey (CSIM-AIT) Design Patterns I 19 / 50

    B i GRASP P tt

    http://find/
  • 7/28/2019 06-PatternsI

    20/50

    Basic GRASP PatternsInformation Expert principle

    The Information Expert pattern: who should be responsible forknowing about instances of a class?

    We assign knowing responsibilities to the class having the informationneeded to fulfill the responsibility.

    When assigning knowing responsibilities, first look in the design modelfor an appropriate class.

    If not found in the design model, look in the domain model.

    Matthew Dailey (CSIM-AIT) Design Patterns I 20 / 50

    B i GRASP P tt

    http://find/
  • 7/28/2019 06-PatternsI

    21/50

    Basic GRASP PatternsInformation Expert principle

    Example: in the Monopoly game, Board should have the responsibility toknow about Square instances.

    Larman (2005), Fig. 17.6

    Matthew Dailey (CSIM-AIT) Design Patterns I 21 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    22/50

    Basic GRASP PatternsInformation Expert principle

    Example: who should have the responsibility to know the total price for asale?

    Domain model:

    Sale

    time

    Sales

    LineItem

    quantity

    ProductDescription

    descriptionpriceitemID

    Described-by*

    Contains

    1..*

    1

    1

    Larman (2005), Fig. 17.14

    Matthew Dailey (CSIM-AIT) Design Patterns I 22 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    23/50

    Basic GRASP PatternsInformation Expert principle

    We see that Sale already has the SalesLineItem objects needed to calculatethe total:

    Sale

    time...

    getTotal()

    :Salet =getTotal

    New method

    Larman (2005), Fig. 17.15

    Matthew Dailey (CSIM-AIT) Design Patterns I 23 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    24/50

    Basic GRASP PatternsInformation Expert principle

    But to get the price of a SalesLineItem, we also need theProductDescriptions price attribute. SalesLineItem has the neededinformation:

    Sale

    time...

    getTotal()

    SalesLineItem

    quantity

    getSubtotal()New method

    1 *: st =getSubtotal: Sale

    t =getTotal lineItems[ i ] :SalesLineItem

    this notation will imply weare iterating over all

    elements of a collection

    Larman (2005), Fig. 17.16

    Matthew Dailey (CSIM-AIT) Design Patterns I 24 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    25/50

    Basic GRASP PatternsInformation Expert principle

    To fulfill the responsibility to know its subtotal, the SalesLineItem needs tocollaborate with ProductDescription:

    Sale

    time...

    getTotal()

    SalesLineItem

    quantity

    getSubtotal()

    ProductDescription

    descriptionpriceitemID

    getPrice()New method

    :ProductDescription

    1.1: p :=getPrice()

    1 *: st =getSubtotal: Sale

    t =getTotal lineItems[ i ] :SalesLineItem

    Larman (2005), Fig. 17.17

    Matthew Dailey (CSIM-AIT) Design Patterns I 25 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    26/50

    Basic GRASP PatternsLow Coupling principle

    The Low Coupling principle: how to reduce the impact of change?

    We assign responsibilities so that unnecessary coupling is low.

    Coupling means how strongly tied one element is to another.

    Coupling makes designs and code hard to understand and hard to modify.

    Use the low coupling principle to evaluate alternative designs.

    Matthew Dailey (CSIM-AIT) Design Patterns I 26 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    27/50

    Basic GRASP PatternsLow Coupling principle

    Note that Information Expert reduces coupling. Consider an alternativedesign for the responsibility of knowing about Square objects:

    Larman (2005), Fig. 17.7

    Matthew Dailey (CSIM-AIT) Design Patterns I 27 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    28/50

    Basic GRASP PatternsLow Coupling principle

    Example: how to create a Payment object and associate it with a Sale?

    On the one hand, we might give Register the responsibility to create thePayment:

    : Register p : Payment

    :Sale

    makePayment() 1: create()

    2: addPayment(p)

    Larman (2005), Fig. 17.18

    Matthew Dailey (CSIM-AIT) Design Patterns I 28 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    29/50

    Basic GRASP PatternsLow Coupling principle

    On the other hand, we might give Sale the responsibility to create thePayment:

    : Register :Sale

    :Payment

    makePayment() 1: makePayment()

    1.1. create()

    Larman (2005), Fig. 17.19

    Which is better? It is unavoidable that Sale is coupled to Payment. Butthe first design creates an unnecessary coupling of Sale to Register. Allelse being equal, we prefer the second.

    Matthew Dailey (CSIM-AIT) Design Patterns I 29 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    30/50

    Basic GRASP PatternsLow Coupling principle

    Common kinds of coupling between TypeX and TypeY:

    TypeX has an attribute that refers to a TypeY instance or TypeYitself.

    A TypeX object calls on the services of a TypeY object.

    TypeX has a method referencing (via parameters, local variables, orreturn values) a TypeY instance.

    TypeX is a direct or indirect subclass of TypeY.

    TypeY is an interface, and TypeX implements that interface.

    Avoiding coupling is not always necessary. It is most important at points ofinstability. Therefore coupling to stable APIs like java.util is generally OK.

    Matthew Dailey (CSIM-AIT) Design Patterns I 30 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    31/50

    Basic GRASP PatternsController pattern

    The Controller pattern: who should be responsible for receiving andcoordinating a system operation?

    We create controller objects to handle system operation messages.

    In most systems, actors will generate UI events. UI objects react to theseelements then delegate to objects in the domain layer (or the intermediateapplication layer, if you have one).

    The first object in the domain layer is called the controller for the systemoperation.

    Matthew Dailey (CSIM-AIT) Design Patterns I 31 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    32/50

    Controller pattern

    There are two main types of controller:

    A controller representing an entire system, root object, device, orsubsystem is called a facade controller. Use a class name such as the

    name of the SuD.A controller responsible for one use case scenario is called a sessioncontroller. Use names such as Handler orSession.

    Note that the GRASP controller is not the same as the C in MVC!

    Matthew Dailey (CSIM-AIT) Design Patterns I 32 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    33/50

    Controller pattern

    Example: for the Monopoly game, there are few system operations:

    Larman (2005), Fig. 17.8

    Matthew Dailey (CSIM-AIT) Design Patterns I 33 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    34/50

    Controller pattern

    For playGame(), we need to identify the recipient of the system operationmessage:

    Larman (2005), Fig. 17.9

    Matthew Dailey (CSIM-AIT) Design Patterns I 34 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    35/50

    Controller pattern

    In this case, since there are so few operations, we use the root objectcontroller pattern:

    Larman (2005), Fig. 17.10

    Matthew Dailey (CSIM-AIT) Design Patterns I 35 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    36/50

    Controller pattern

    Example: for the enterItem operation, we have a situation like this:

    Which class of object should be responsible for receiving this

    system 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 layer.

    actionPerformed( actionEvent )

    : ???

    : Cashier

    :SaleJFrame

    presses button

    enterItem(itemID, qty)?

    UI Layer

    DomainLayer

    system operation message

    Larman (2005), Fig. 17.21

    Matthew Dailey (CSIM-AIT) Design Patterns I 36 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    37/50

    Controller pattern

    Some possible design alternatives:

    :RegisterenterItem(id, quantity)

    :ProcessSaleHandlerenterItem(id, quantity)

    Larman (2005), Fig. 17.22

    Matthew Dailey (CSIM-AIT) Design Patterns I 37 / 50

    Basic GRASP Patterns

    http://goforward/http://find/http://goback/
  • 7/28/2019 06-PatternsI

    38/50

    Controller pattern

    Combining with the other system operations, we can see the consequences

    of each design alternative:Register

    ...

    endSale()enterItem()makeNewSale()makePayment()

    makeNewReturn()enterReturnItem(). . .

    System

    endSale()enterItem()makeNewSale()makePayment()

    makeNewReturn()enterReturnItem(). . .

    system operationsdiscovered during systembehavior analysis

    allocation of systemoperations during design,using one facade controller

    ProcessSaleHandler

    ...

    endSale()

    enterItem()makeNewSale()makePayment()

    System

    endSale()enterItem()makeNewSale()

    makePayment()

    enterReturnItem()makeNewReturn(). . .

    allocation of systemoperations during design,using several use casecontrollers

    HandleReturnsHandler

    ...

    enterReturnItem()

    makeNewReturn(). . .

    Larman (2005), Fig. 17.23

    Matthew Dailey (CSIM-AIT) Design Patterns I 38 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    39/50

    Controller pattern

    Some tips about controllers:The controller should be seen as a facade into the domain layer.

    Use the same controller for all system events involved in a use case.

    Controllers will often be stateful, maintaining information about the

    current progress of the use case.For purposes of cohesion, controllers should primarily delegate,(forward responsibility to other objects) wherever possible.

    In Java EE, controllers will oftentimes be stateful session EnterpriseJava Beans.

    The controller may delegate directly to domain layer objects, or if it isin a separate application logic layer, it may make requests to othercontrollers in the pure domain layer.

    Matthew Dailey (CSIM-AIT) Design Patterns I 39 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    40/50

    Controller pattern

    Some controller antipatterns:

    A single controller with too many system events.No delegation.

    Duplication of information found elsewhere in the domain layer.

    Matthew Dailey (CSIM-AIT) Design Patterns I 40 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    41/50

    Controller pattern

    Dont allow direct manipulation of domain objects in the UI layer!

    Example (good design):

    actionPerformed( actionEvent )

    :Register

    : Cashier

    :SaleJ Frame

    presses button

    1: enterItem(itemID, qty)

    :Sale1.1: makeLineItem(itemID, qty)

    UI Layer

    Domain Layer

    system operation message

    controller

    Larman (2005), Fig. 17.24

    Matthew Dailey (CSIM-AIT) Design Patterns I 41 / 50

    Basic GRASP Patterns

    http://find/
  • 7/28/2019 06-PatternsI

    42/50

    Controller pattern

    Example (bad design):

    Cashier

    :SaleJ Frame

    actionPerformed( actionEvent )

    :Sale1: makeLineItem(itemID, qty)

    UI Layer

    Domain Layer

    It is undesirable for an interfacelayer object such as a window to getinvolved in deciding how to handledomain processes.

    Business logic is embedded in thepresentation layer, which is not useful.

    SaleJ Frame should notsend this message.

    presses button

    Larman (2005), Fig. 17.25

    Matthew Dailey (CSIM-AIT) Design Patterns I 42 / 50

    Basic GRASP PatternsC ll

    http://find/
  • 7/28/2019 06-PatternsI

    43/50

    Controller pattern

    In message processing systems, rather than a use case controller, we would

    most likely use the Command pattern in which we have one object foreach possible type of incoming command (see Larman Ch. 37 for details).

    Matthew Dailey (CSIM-AIT) Design Patterns I 43 / 50

    Basic GRASP PatternsHi h C h i i i l

    http://find/
  • 7/28/2019 06-PatternsI

    44/50

    High Cohesion principle

    The High Cohesion principle: how to keep objects focused,understandable, and manageable?

    We assign responsibilities so that cohesion remains high, i.e., so thatsimilar responsibilities are grouped into the same class.

    High cohesion is a principle used to evaluate competing designs.

    Matthew Dailey (CSIM-AIT) Design Patterns I 44 / 50

    Basic GRASP PatternsHi h C h i i i l

    http://find/
  • 7/28/2019 06-PatternsI

    45/50

    High Cohesion principle

    Example of good and bad cohesion:

    Larman (2005), Fig. 17.11

    Matthew Dailey (CSIM-AIT) Design Patterns I 45 / 50

    Basic GRASP PatternsHigh Cohesion principle

    http://find/
  • 7/28/2019 06-PatternsI

    46/50

    High Cohesion principle

    Example: for the POS system, when we design for the makePayment()

    system operation:

    : Register : Sale

    addPayment( p )

    p : Paymentcreate()

    makePayment()

    Larman (2005), Fig. 17.26

    We already saw that this creates an unnecessary coupling between Registerand Payment.

    But it also reduces the cohesion of Register.

    Matthew Dailey (CSIM-AIT) Design Patterns I 46 / 50

    Basic GRASP PatternsHigh Cohesion principle

    http://find/
  • 7/28/2019 06-PatternsI

    47/50

    High Cohesion principle

    By delegating Payment creation to Sale, we not only decrease coupling,but we also increase the cohesion of Register.

    : Register : Sale

    makePayment()

    : Paymentcreate()

    makePayment()

    Larman (2005), Fig. 17.27

    Since Register has fewer responsibilities, it is more cohesive.

    Matthew Dailey (CSIM-AIT) Design Patterns I 47 / 50

    Basic GRASP PatternsHigh Cohesion principle

    http://find/
  • 7/28/2019 06-PatternsI

    48/50

    High Cohesion principle

    Cohesion and coupling often go together: you will often see cases whereincreased coupling also causes low cohesion, and vice versa.

    Matthew Dailey (CSIM-AIT) Design Patterns I 48 / 50

    Outline

    http://find/
  • 7/28/2019 06-PatternsI

    49/50

    1 Introduction

    2 Responsibility-Driven Design

    3 Basic GRASP Patterns

    4 Wrap-Up

    Matthew Dailey (CSIM-AIT) Design Patterns I 49 / 50

    Wrap-UpNext step

    http://find/
  • 7/28/2019 06-PatternsI

    50/50

    Next step

    Now that we know the basic principles of responsibility assignment, were

    ready to do detailed designs for some of our use cases.Later, well look at more advanced design patterns.

    Matthew Dailey (CSIM-AIT) Design Patterns I 50 / 50

    http://find/