Design interaction diagrams and class diagrams by bdj93780

VIEWS: 106 PAGES: 45

									4. Design:
    interaction and
    class diagrams
Situation

   artifacts vs. practice

        UML-based artifacts for design
             interaction diagrams
                   Collaboration diagrams
                   Sequence diagrams
             class diagrams
             statechart diagrams
             …

        practice
             GRASP patterns
             Design Patterns
             Refactorings
1. Interactiediagramma‟s
         in het Ontwerpproces

   Voor elke niet-triviale functionaliteit van de software …

       doel:
            identificatie/ontwerp van een groep van samenwerkende objecten
                     om die functionaliteit te verwezenlijken


       startbericht: trigger vanuit functionaliteit
            bvb. actie uit use case

          use-case driven
Interactie diagramma‟s
   Een interactiediagramma
       illustreert de bericht-interacties tussen objecten en klassen


   In UML bestaan 2 soorten:
       Communication Diagrams               – nadruk op object-interacties
       Sequence Diagrams                    – nadruk op tijdsverloop



                                          1: message2()
           message1()                     2: message3()
                        :ClassAInstance                   :ClassBInstance
Interactie diagramma‟s
   Een interactiediagramma
       illustreert de bericht-interacties tussen objecten en klassen


   In UML bestaan 2 soorten:
       Communication Diagrams                   – nadruk op object-interacties
       Sequence Diagrams                        – nadruk op tijdsverloop


                               :ClassAInstance                   :ClassBInstance
                  message1()

                                                    message2()


                                                    message3()
1.1 Communication Diagrams
       Bestaat   uit:
           startbericht en genummerde berichten
           verbindingen tussen objecten waarlangs berichten



                                                                              richting
                                             eerste intern bericht
   startbericht



makePayment(cashTendered)                    1: makePayment(cashTendered)
                                 :Register                                          :Sale




                                             verbinding       1.1: create(cashTendered)

                            instantie
                                                                                  :Payment

                                                            parameter
Communication Diagrams: Notatie

 Klassen   en instanties

               Sale                    :Sale                 s1: Sale




 Een   return waarde


                       msg1()


                                1: tot := total(): Integer
                :Register                                      :Sale
Communication Diagrams: Notatie
   Berichten naar “this”                               msg1()


                                               :Register




                                               1: clear()

   Berichten naar klassen


                         msg1()


                                  1: d1 := today(): Date
                     :Sale                                       Date
    Communication Diagrams: Notatie
                                                          msg1()

                                                                      1: create(cashier)
   Creatie van objecten                            :Register                                 s:Sale
                                                                   2: addPayment(amount)

     Optioneel: gebruik stereotype <<create>>
     voor een niet triviale constructor boodschap



   Taalonafhankelijk: geen new bericht naar klasse

                                           msg1()

                                                      1: s:= new(cashier)
                                    :Register                                        Sale



                                                                                     s:Sale
                                                    2: addPayment(amount)
Communication Diagrams: Notatie

   Berichtnummering

          msg1()             1: msg2()
                   :ClassA                      :ClassB




                                  1.1: msg3()


                                                :ClassC
Communication Diagrams: Notatie

   Berichtnummering: vervolg
        msg1()                  1: msg2()
                  :ClassA                          :ClassB


                                                          1.1: msg3()

                                                          2.1: msg5()
                            2: msg4()
                                                   :ClassC


                                            2.2: msg6()



                                                   :ClassD
Communication Diagrams: Notatie

   Conditionele berichten

                 msg1()

                          1 [new sale]: create()
           :Register                                         :Sale



                                             1.1: create()



                                                     :SalesLineItem
Communication Diagrams: Notatie

   Conditionele berichten: vervolg

                  :ClassE


           2: msg6()

         msg1()                   1a [test1]: msg2()
                  :ClassA                              :ClassB



                       1b [not test1]: msg4()               1a.1: msg3()


                                      1b.1: msg5()
                  :ClassD                              :ClassC
Communication Diagrams: Notatie

   Iteraties
                    runSimulation()



                          1* [i := 1..n]: num = nextInt()
            :Simulator                                      :Random
Communication Diagrams: Notatie

   Iteration over a collection
                     t = getTotal



                            1* [i := 1..n]: st = getSubtotal()   lineItems[i]:
             :Sale
                                                                 SalesLineIte
Communication Diagrams: Notatie

   Polymorphic Messages and Cases


                           Payment {abstract}

                           authorize {abstract}
                           …




           CreditPayment                  DebitPayment
           authorize                      authorize
           …                              …
Communication Diagrams: Notatie

   Polymorphic Messages and Cases

              doX()                     authorize
                          :Register                      :Payment {abstract}




            authorize()                                     authorize()




     :DebitPayment                    :Foo          :CreditPayment              :Bar
                          doA                                             doX
                          doB
Communication Diagrams: Notatie

    Active objects        :Clock



    Asynchronous and synchronous calls

                               startClock


                        :ClockStarter                :Bar
                                            3: doX


                             1: create      2: run


                          :Clock
1.2 Sequence Diagrams
    Boodschappen: geen nummering !


                               : Register            : Sale
             : User


                      msg1()
                                            msg2()

                                            msg3()

                                            msg4()

                                            msg5()
Sequence Diagrams: Notatie

   Berichten naar “self” of “this”



                                           : Register
                         : User


                                  msg1()
                                                 clear()
Sequence Diagrams: Notatie

   Creatie van objecten

           : Register                               : Sale


                        makePayment(cashTendered)
                                                             create(cashTendered)   : Payment

                                                                     authorize()
Sequence Diagrams: Notatie

   Conditionele berichten (UML 2)



                                      • : Foo                  • : Bar
             • : User


                        •message1()   opt [color = red]
                                                 calculate()
Sequence Diagrams: Notatie

   Lifeline van objecten


                                       : Sale                 : Payment
                 : User

                          message1()
                                            create(cashTendered)

                                                  destroy
Sequence Diagrams: Notatie

   Iteratie (UML 2)


            : User
                                   : Simulator                   : Random      : Programmer

                     runSimulation()
                                            [i:=1..N]
                                       loop hours := nextInt()


                                                                 work(hours)



                                                                       eat()
2. Ontwerp Klassendiagramma's

 Identificeer    software klassen
      op basis van
           interactiediagramma‟s
           conceptueel model


      Voor de meeste concepten zal er een klasse zijn die dit concept concretiseert
           attributen: overgenomen van concept, uitgebreid met type-informatie
           methodes: afgeleid uit interactiediagramma‟s


      Voeg associaties en navigatie toe
           alleen die associaties worden gerealiseerd die nodig zijn om aan de informatiebehoeften
            van de interactiediagramma‟s te voldoen
Identificatie relevante software klassen
                                                           Records-sale-of

                                                       Described-by                              1
                                                                                           Product
                                                           Product                       Specification
                                                           Catalog         Contains
                                                                      1           1..*
                                                            1
              0..1          *                                    Used-by                     1
                                                                 *                                   Describes
                 Sales                                                                           *
                LineItem                                   Store                             Item
                                                                           Stocks
                                                   1                  1             *                     1
                         1..*
                                                 Logs-          1 Houses
      Contained-in                             completed
                  1                               6              1..*
                                  *
                     Sale                                  Register
                                                                                           Manager
                                                                        Started-by
                                                                      1           1
                                      Captured-on
                                  1             1
                     1      1                               1 3
      Paid-by                   Initiated-by                    Records-sales-on
     1                                 1                                        1
    Payment                      Customer                                        Cashier
Class diagrams – Overview
                                                                                          officially in UML , the top format is
                                                     SuperclassFoo                        used to distinguish the package
                                                            or                            name from the class name
                                                SuperClassFoo { abstract }
                                                                                          unofficially , the second alternative
                                 - classOrStaticAttribute : Int                           is common
                                 + publicAttribute : String
        3 common
                                 - privateAttribute
        compartments
                                 assumedPrivateAttribute
                                 isInitializedAttribute : Bool = true                                            java .awt ::Font
        1. classifier name
                                 aCollection : VeggieBurger [ * ]                                                        or
                                 attributeMayLegallyBeNull : String [0..1]                                        java .awt .Font
        2. attributes
                                 finalConstantAttribute : Int = 5 { readOnly }
                                 /derivedAttribute                                                  plain : Int = 0 { readOnly }
        3. operations
                                                                                                    bold : Int = 1 { readOnly }
                                 + classOrStaticMethod ()                                           name : String
                                 + publicMethod ()                                                  style : Int = 0
                                 assumedPublicMethod ()                                             ...
         an interface            - privateMethod ()
         shown with a            # protectedMethod ()                                               getFont (name : String ) : Font
         keyword                 ~ packageVisibleMethod ()                                          getName () : String
                                 «constructor» SuperclassFoo ( Long )                               ...
                                 methodWithParms (parm 1 : String , parm 2 : Float )
                                 methodReturnsSomething () : VeggieBurger
          «interface»            methodThrowsException () {exception IOException }
           Runnable              abstractMethod ()
                                 abstractMethod 2() { abstract } // alternate                                                  Fruit
        run ()                   finalMethod () { leaf } // no override in subclass      dependency
                                 synchronizedMethod () { guarded }                                                  ...

                                                                                                                    ...


       interface
       implementation
       and
       subclassing                                     SubclassFoo
                                                                                                                          PurchaseOrder
                                  ...                                                                        1
                                                                                                                    ...
                                  run ()                                                                   order
                                                                                                                    ...
                                  ...
                                                                                        association with
                                                                                        multiplicities
                         - ellipsis “…” means there may be elements   , but not shown
                         - a blank compartment officially means “unknown” but as a
                         convention will be used to mean “no members”
Domain model is the analysis class diagram
Don‟t show methods


        Domain Model                                                       Sale
                                 Register         Captures    1
                                              1
                                                                   time
        conceptual
                          ...                                      isComplete : Boolean
        perspective
                                                                   /total



                                 Register                                  Sale
        Design Model       ...                                     time
                                                             1
                                                                   isComplete : Boolean
        DCD; software      endSale()                 currentSale   /total
        perspective        enterItem(...)
                           makePayment(...)                        makeLineItem(...)


                        Avoid showing no-argument constructors & getters/setters

Design model class diagrams shows methods and visibility (arrowhead on
association)
Register has reference to Sale; Sale does not have reference to Register
                    Register                                            Sale

   Avoid    currentSale : Sale                                    ...

            ...                                                   ...



                                    Rolename is attribute name
                    Register                                            Sale
                                                              1
            ...                                                   ...
Preferred                                           currentSale
            ...                                                   ...

                  using the association notation to indicate
                  Register has a reference to one Sale instance



                    Register                                            Sale
                                                              1
            currentSale : Sale                                    ...
    Avoid                                           currentSale
            ...                                                   ...
Associations in design class diagrams



                                            Register                              Sale
applying the guideline
to show attributes as                                               1
                                  id: Int                                 time: DateTime
attribute text versus as                                    currentSale
association lines                 ...                                     ...



                           Register has THREE attributes:                        Store
                           1. id                                     1
                           2. currentSale                                 address: Address
                           3. location                                    phone: PhoneNumber
                                                               location
                                                                          ...




   Showing Sale & Store attributes as associations visually emphasizes
   relationships important in object collaboration
Class Diagrams


     UML notation for attributes
          You don‟t have to use entire notation
          Visibility
                + (public)
                - (private)


  visibility attribName : type multiplicity = default {property-string}
     Collection attributes
          in design class diagrams

                                           Sale                                       SalesLineItem

                       time: DateTime                                           ...
                       lineItems : SalesLineItem [1..*]
                                   or                                           ...
                       lineItems : SalesLineItem [1..*] {ordered}

                       ...
Two ways to show a
collection attribute


                                Sale                                                  SalesLineItem
                                                                         1..*
                       time: DateTime                                           ...
                                                                   lineItems
                       ...                                    {ordered, List}   ...


                                       notice that an association end can optionally also
                                       have a property string such as {ordered, List}


  Preferred, less visual clutter
Generalization / Inheritance


   More UML notation
       Generalization
            Same as inheritance when in design mode
            Solid line with open arrow

               Superclass                              Subclass




     To indicate abstract, use italics
     For final classes or operations, use {leaf}
Dependency relations

   Dependency
       When a client has knowledge of a server
       Changes in server affects client
       Client and server are „coupled‟

       NOT a good thing! Leads to brittle design

       Occurs anytime client has direct visibility to server
            We‟ll cover types of visibility later
  Dependency relations (cont.)


                       the Sale has parameter visibility to a
                       ProductDescription, and thus some kind of
                       dependency
                                                                            ProductDescription

                                                                          ...
                               Sale
                                                                          ...
               ...

               updatePriceFor( ProductDescription )
               ...                                                              SalesLineItem

                                                                   1..*   ...
                                                            lineItems
                                                                          ...




If ProductDescription’s public interface changes, then Sale may need to be modified
Dependency relations (cont.)


the doX method invokes the runFinalization
static method, and thus has a dependency on
the System class
                                                     System

                                              ...
                   Foo
                                              runFinalization()
           ...                                ...

           doX()
           ...




 Dependency due to calling a static method
Dependency relations (stereotypes)




                                               Clock                                                 B
     Window                «call»                               A            «create»
                                           getTime()                                           ...
                                           ...

a dependency on calling on operations of               a dependency that A objects create B objects
the operations of a Clock




Using keywords or stereotypes to indicates type of dependency
Aggregation / Composition – Associations

              1         0..7             composition means
  Hand                         Finger
                                         -a part instance (Square) can only be part of one
                                         composite (Board) at a time

          composition                    -the composite has sole responsibility for management of
                                         its parts, especially creation and deletion


              1          40                                        1       1..*
  Board                        Square               Sale                           SalesLineItem




 • Aggregation is regular association
 • Composition is the „strong‟ form of aggregation
Constraints in Class Diagrams


                               three ways to show UML constraints

              Stack

size : Integer { size >= 0 }

push( element )                 { post condition: new size = old size + 1 }
pop() : Object


                                 {
                                 post condition: new size = old size – 1
                                 }
Association Classes




                                     Employs
        Company           *                              *   Person




a person may have                  Employment
employment with several
companies                     salary
                              startDate




Association class simplifies many-to-many multiplicity
Singleton Class




                                                                         1
                                            ServicesFactory                   UML notation: this '1'
                                                                              can optionally be used
UML notation: in a        instance : ServicesFactory                          to indicate that only one
class box, an                                                                 instance will be created
underlined attribute or   accountingAdapter : IAccountingAdapter              (a singleton)
method indicates a        inventoryAdapter : IInventoryAdapter
static (class level)      taxCalculatorAdapter : ITaxCalculatorAdapter
member, rather than
an instance member        getInstance() : ServicesFactory

                          getAccountingAdapter() : IAccountingAdapter
                          getInventoryAdapter() : IInventoryAdapter
                          getTaxCalculatorAdapter() : ITaxCalculatorAdapter
                          ...




   Singleton class: Only 1 instance can exist
Template/Generic Types

                                                             the attribute type may be expressed in
           parameterized or template                     K   official UML , with the template binding
           interfaces and classes        «interface»         syntax requiring an arrow
                                             List                       or
           K is a template parameter                         in another language , such as Java
                                       clear()
                                       ...

                                                                                            Board

                                                                                squares : List<K Square>
anonymous class with                                                                      or
template binding complete                                T                      squares : List<Square>
                                          ArrayList                             ...
                                       elements : T[*]
     ArrayList<T Square>               ...
 clear()                               clear()
 ...                                                         for example , the elements attribute is an
                                       ...
                                                             array of type T , parameterized and bound
                                                             before actual use .




 Template types are new since Java 1.5
Additional compartments for a class

                    DataAccessObject

              id : Int
              ...

              doX()
              ...

                 exceptions thrown
              DatabaseException
              IOException

                     responsibilities
              serialize and write objects
              read and deserialize objects
              ...
Active Classes



                                                    active class

                                            Clock
  «interface»
   Runnable                           ...
run()                                 run()
                                      ...


 Active class executes in its own thread
Relationship between class & interaction diagrams
                                  : Register                                : Sale


      makePayment(cashTendered)

                                               makePayment(cashTendered)


  messages in interaction
  diagrams indicate operations
  in the class diagrams                                                              classes
                                                                                     identified in the
                                                                                     interaction
                                                                                     diagrams are
                   Register                                          Sale            declared in the
                                                          1                          class diagrams
            ...                                                ...
                                                 currentSale
            makePayment(…)                                     makePayment(…)
            ...                                                ...




 Models must be consistent with each other

								
To top