object modelling 2

profilealisgh
grasp_pattern.ppt

References:

  • Applying UML and patterns

Craig Larman

  • Patterns in Java, volume 2

Mark Grand

What are patterns?

  • Principles and solutions codified in a structured format describing a problem and a solution
  • A named problem/solution pair that can be applied in new contexts
  • It is advice from previous designers to help designers in new situations

The idea behind design patterns is simple:

Write down and catalog common interactions between objects that programmers have frequently found useful.

Result:

Facilitate reuse of object-oriented code between projects and between programmers.

Some definitions of design patterns

  • “Design patterns constitute a set of rules describing how to accomplish

certain tasks in the realm of software development.” (Pree, 1994)

  • “Design patterns focus more on reuse of recurring architectural design

themes, while frameworks focus on detailed design… and

implementation.” (Coplien & Schmidt, 1995).

  • “A pattern addresses a recurring design problem that arises in specific

design situations and presents a solution to it” (Buschmann, et. al. 1996)

  • “Patterns identify and specify abstractions that are above the level of

single classes and instances, or of components.” (Gamma, et al., 1993)

Characteristics of Good patterns

  • It solves a problem
  • It is a proven concept
  • The solution isn't obvious
  • It describes a relationship
  • The pattern has a significant human component
  • It solves a problem: Patterns capture solutions, not just abstract principles or strategies.
  • It is a proven concept: Patterns capture solutions with a track record, not theories or speculation.
  • The solution isn't obvious: Many problem-solving techniques (such as software design paradigms or methods) try to derive solutions from first principles. The best patterns generate a solution to a problem indirectly -- a necessary approach for the most difficult problems of design.
  • It describes a relationship: Patterns don't just describe modules, but describe deeper system structures and mechanisms.
  • The pattern has a significant human component .... All software serves human comfort or quality of life; the best patterns explicitly appeal to aesthetics and utility.

Types of patterns

Architectural Patterns

Expresses a fundamental structural organization or schema for software systems.

Design Patterns

Provides a scheme for refining the subsystems or components of a software system, or the relationships between them.

Idioms

An idiom describes how to implement particular aspects of components or the relationships between them using the features of the given language.

Architectural Patterns

An architectural pattern expresses a fundamental structural organization or schema for software systems. It provides a set of predefined subsystems, specifies their responsibilities, and includes rules and guidelines for organizing the relationships between them.

Design Patterns

A design pattern provides a scheme for refining the subsystems or components of a software system, or the relationships between them. It describes commonly recurring structure of communicating components that solves a general design problem within a particular context.

Idioms

An idiom is a low-level pattern specific to a programming language. An idiom describes how to implement particular aspects of components or the relationships between them using the features of the given language.

Describing patterns

Name : It must have a meaningful name.

Problem: A statement of the problem.

Context: This tells us the pattern's applicability.

Forces: A description of the relevant forces and constraints and how they interact/conflict with one another..

Solution: Static relationships and dynamic rules describing how to realize the desired outcome.

Consequences: Implications( good and bad) of using the solution.

Examples: One or more sample applications of the pattern .

Name

It must have a meaningful name. This allows us to use a single word or short phrase to refer to the pattern, and the knowledge and structure it describes. It would be very unwieldy to have to describe or even summarize the pattern every time we used it in a discussion. Good pattern names form a vocabulary for discussing conceptual abstractions. Sometimes a pattern may have more than one commonly used or recognizable name in the literature. In this case it is common practice to document these nicknames or synonyms under the heading of Aliases or Also Known As. Some pattern forms also provide a classification of the pattern in addition to its name.

Problem

A statement of the problem which describes its intent: the goals and objectives it wants to reach within the given context and forces. Often the forces oppose these objectives as well as each other (one might think of this as a "wicked problem" reminiscent of DeGrace and Stahl, in their book Wicked Problems, Righteous Solutions).

Context

The preconditions under which the problem and its solution seem to recur, and for which the solution is desirable. This tells us the pattern's applicability. It can be thought of as the initial configuration of the system before the pattern is applied to it.

Forces

A description of the relevant forces and constraints and how they interact/conflict with one another and with goals we wish to achieve (perhaps with some indication of their priorities). A concrete scenario which serves as the motivation for the pattern is frequently employed (see also Examples). Forces reveal the intricacies of a problem and define the kinds of trade-offs that must be considered in the presence of the tension or dissonance they create. A good pattern description should fully encapsulate all the forces which have an impact upon it. A list of prospective pattern forces for software may be found in the answer to question 11 of Doug Lea's Patterns-Discussion FAQ.

Solution

Static relationships and dynamic rules describing how to realize the desired outcome. This is often equivalent to giving instructions which describe how to construct the necessary work products. The description may encompass pictures, diagrams and prose which identify the pattern's structure, its participants, and their collaborations, to show how the problem is solved. The solution should describe not only static structure but also dynamic behavior. The static structure tells us the form and organization of the pattern, but often it is the behavioral dynamics that make the pattern "come alive". The description of the pattern's solution may indicate guidelines to keep in mind (as well as pitfalls to avoid) when attempting a concrete implementation of the solution. Sometimes possible variants or specializations of the solution are also described.

Examples

One or more sample applications of the pattern which illustrate: a specific initial context; how the pattern is applied to, and transforms, that context; and the resulting context left in its wake. Examples help the reader understand the pattern's use and applicability. Visual examples and analogies can often be especially illuminating. An example may be supplemented by a sample implementation to show one way the solution might be realized. Easy-to-comprehend examples from known systems are usually preferred (see also Known Uses).

Resulting Context

The state or configuration of the system after the pattern has been applied, including the consequences (both good and bad) of applying the pattern, and other problems and patterns that may arise from the new context. It describes the postconditions and side-effects of the pattern. This is sometimes called resolution of forces because it describes which forces have been resolved, which ones remain unresolved, and which patterns may now be applicable (see the answer to question 12 of Doug Lea's Patterns-Discussion FAQ for an excellent discussion of resolution of forces). Documenting the resulting context produced by one pattern helps you correlate it with the initial context of other patterns (a single pattern is often just one step towards accomplishing some larger task or project).

Rationale

A justifying explanation of steps or rules in the pattern, and also of the pattern as a whole in terms of how and why it resolves its forces in a particular way to be in alignment with desired goals, principles, and philosophies. It explains how the forces and constraints are orchestrated in concert to achieve a resonant harmony. This tells us how the pattern actually works, why it works, and why it is "good". The solution component of a pattern may describe the outwardly visible structure and behavior of the pattern, but the rationale is what provides insight into the deep structures and key mechanisms that are going on beneath the surface of the system.

Related Patterns

The static and dynamic relationships between this pattern and others within the same pattern language or system. Related patterns often share common forces. They also frequently have an initial or resulting context that is compatible with the resulting or initial context of another pattern. Such patterns might be predecessor patterns whose application leads to this pattern; successor patterns whose application follows from this pattern; alternative patterns that describe a different solution to the same problem but under different forces and constraints; and codependent patterns that may (or must) be applied simultaneously with this pattern.

Known Uses

Describes known occurrences of the pattern and its application within existing systems. This helps validate a pattern by verifying that it is indeed a proven solution to a recurring problem. Known uses of the pattern can often serve as instructional examples

GRASP Patterns

Which class, in the general case is responsible?

  • You want to assign a responsibility to a class
  • You want to avoid or minimize additional dependencies
  • You want to maximise cohesion and minimise coupling
  • You want to increase reuse and decrease maintenance
  • You want to maximise understandability
  • …..etc.

GRASP patterns
General Responsibility Assignment Software Patterns

  • Expert
  • Creator
  • Low Coupling
  • High Cohesion
  • Controller
  • Polymorphism
  • Pure Fabrication
  • Indirection
  • Law of Demeter

Expert

Problem:

What is the most basic principle by which responsibilities are assigned in object-oriented design?

Solution:

Assign a responsibility to the class that has the information necessary to fulfil the responsibility.

Expert : Example

Who is responsible for knowing the grand total of a sale in a typical Point of Sale application?

Expert

Which class, in the general case is responsible?

.

  • ·        You want to assign a responsibility to a class
  • ·        You want to assign the responsibility to a class that is already present in your design if possible
  • ·        A class already has access to the information required to carry out the responsibility
  • ·        You want to avoid or minimize additional dependencies

 

Expert : Example

Need all SalesLineItem instances and their subtotals. Only Sale knows

this, so Sale is the information expert.

Hence

Expert : Example

But subtotals are needed for each line item(multiply quantity by price).

By Expert, SalesLineItem is expert, knows quantity and has association

with ProductSpecification which knows price.

Expert : Example

Hence responsibilities assign to the 3 classes.

 

Class

Responsibility

Sale

knows sale total

SalesLineItem

knows line item subtotal

ProductSpecification

knows product price

Expert

  • Maintain encapsulation of information
  • Promotes low coupling
  • Promotes highly cohesive classes
  • Can cause a class to become excessively complex

Creator

Problem:

Assign responsibility for creating a new instance of some class?

Solution:

Determine which class should create instances of a class based on the relationship between potential creator classes and the class to be instantiated.

Creator

who has responsibility to create an object?

By creator, assign class B responsibility of creating instance of class A if

B aggregates A objects

B contains A objects

B records instances of A objects

B closely uses A objects

B has the initializing data for creating A objects

where there is a choice, prefer

B aggregates or contains A objects

Creator : Example

Who is responsible for creating SalesLineItem objects?

Look for a class that aggregates or contains SalesLineItem objects.

Creator : Example

Creator pattern suggests Sale.

Collaboration diagram is

Creator

  • Promotes low coupling by making instances of a class responsible for creating objects they need to reference
  • By creating the objects themselves, they avoid being dependent on another class to create the object for them

Low Coupling

Problem:

To support low dependency and increased reuse?

Solution:

Assign responsibilities so that coupling

remains low.

In object oriented languages, common form of coupling from TypeX to TypeY include:

  • TypeX has an attribute (data member or instance variable) that refers to a TypeY instance, or TypeY itself.
  • TypeX has a method which references an instance of TypeY, or TypeY itself, by any means. These typically include a parameter or local variable of type TypeY, or the object returned from a message being an instance of TypeY.
  • TypeX is a direct or indirect subclass of TypeY.
  • TypeY is an interface, and TypeX implements that interface.

Low coupling

  • Classes are easier to maintain
  • Easier to reuse
  • Changes are localised

Low Coupling

How can we make classes independent of other classes?

changes are localised

easier to understand

easier to reuse

Who has responsibility to create a payment?

Low Coupling

Two possibilities:

1. Post

2. Sale

Low coupling suggests Sale because Sale has to be coupled to Payment anyway (Sale knows its total).

High Cohesion

Problem:

To keep complexity manageable?

Solution:

Assign responsibilities so that cohesion

remains high.

Some examples:

  • Very Low Cohesion: A Class is solely responsible for many things in very different functional areas
  • Low Cohesion: A class has sole responsibility for a complex task in one functional area.
  • High Cohesion. A class has moderate responsibilities in one functional area and collaborates with classes to fulfil tasks.

High cohesion

  • Classes are easier to maintain
  • Easier to understand
  • Often support low coupling
  • Supports reuse because of fine grained responsibility

High Cohesion

Who has responsibility to create a payment?

1.Post

looks OK if makePayement considered in isolation, but adding more system operations, Post would take on more and more responsibilities and become less cohesive.

High Cohesion

Giving responsibility to Sale supports higher cohesion in Post, as well as

low coupling.

Controller

Problem:

To assign responsibility for handling a system event?

Solution:

If a program receive events from external sources other than its graphical interface, add an event class to decouple the event source(s) from the objects that actually handle the events.

The Controller pattern provides guidance for generally acceptable choices.

Assign the responsibility for handling a system event message to a class representing one of these choices:

1. The business or overall organization (a façade controller).

2. The overall "system" (a façade controller).

3. An animate thing in the domain that would perform the work (a role controller).

4. An artificial class (Pure Fabrication representing the use (a use case controller).

Benefits:

Increased potential for reuse. Using a controller object keeps external event sources and internal event handlers independent of each other’s type and behaviour.

Reason about the states of the use case. Ensure that the system operations occurs in legal sequence, or to be able to reason about the current state of activity and operations within the use case.

Controller : Example

System events in Buy Items use case

enterItem()

endSale()

makePayment()

who has the responsibility for enterItem()?

Controller : Example

By controller, we have 4 choices

the overall system Post

the overall business Store

someone in the real world
who is active in the task Cashier

an artificial handler of all system

events of a use case BuyItemsHandler

The choice of which one to use will be influenced by other factors such as cohesion and coupling

Good design
- presentation layer decoupled from problem domain

  • Assigning the responsibility for system operations to objects

in the domain layer rather than presentation layer supports

increased reuse potential.

• It also makes it easier to unplug the interface layer and use

a different interface technology, or to run the system in an

off-line “batch” mode.

Object Store

Enter Item

End Sale

UPC

Make Payment

Total

Quantity

Tendered

Balance

:POST

Cashier

:POSTCommand

presses button

onEnterItem()

1: enterItem(upc, qty)

:Sale

1.1: makeLineItem(upc, qty)

Presentation Layer

(Command Object)

Domain Layer

system event message

controller

Bad design
– presentation layer coupled to problem domain

Object Store

Enter Item

End Sale

UPC

Make Payment

Total

Quantity

Tendered

Balance

Cashier

:POSTCommand

presses button

onEnterItem()

:Sale

1: makeLineItem(upc, qty)

Presentation Layer

(Command object)

Domain Layer

It is undesirable for a presentation

layer objects such as a Java applet to

get involved in deciding how to handle

domain processes.

Business logic is embedded in the

presentation layer, which is not useful.

POSTApplet should not

send this message.

Controller

  • Using a controller object keeps external event sources and internal event handlers independent of each other’ type and behaviour
  • The controller objects can become highly coupled and uncohesive with more responsiblities

Polymorphism

Problem:

To handle alternatives based on types?

Solution:

When alternate behaviours are selected based on the type of an object, use polymorphic method call to select the behaviour, rather than using if statement to test the type.

polymorphism

has definition A property of object oriented software by which an abstract operation may be performed in different ways in different classes

exists when several classes which each implement the operation either have a common superclass in which the operation exists, or else implement an interface that contains the operation

gets power from dynamic binding

is one of the fundamental features of the object oriented paradigm

dynamic binding

has definition The process of binding a call to a particular method. This is performed dynamically at run-time due to the presence of polymorphism

gives power to polymorphism

is needed when the compiler determines that there more than one possible method that could be executed by a particular call

is a kind of process

prevents programmers from having to write conditional statements to explicitly choose which code to run

Polymorphism : Example

CreditPayment

authorize()

CheckPayment

authorize()

By Polymorphism, each

payment should

authorize itself

CashPayment

authorize()

Payment

amount

In the point -of -sale application, who should be responsible

for authorising different kinds of payments?

– Note: Payments may be in

• cash (authorising involves determining if it is

counterfeit)

• credit (authorising involves communication with bank)

• check (authorising involves driver license record)

Example : Polymorphism

Polymorphism

  • Easier and more reliable then using explicit selection logic
  • Easier to add additional behaviours later on
  • Increased the number classes in a design
  • May make the code less easier to follow

Lessons from Polymorphism

• Future extensions required for unanticipated new

variations are easy to add.

• Avoid “case /switch” statements or “if” conditionals on

type.

• The objects work on themselves

– Example: payments authorise themselves

• Also known as: “Do it myself”, “Choosing Message” and

“don’t ask ‘what kind?’”

Pure Fabrication

Problem:

To not violate High Cohesion and Low Coupling?

Solution:

Assign a highly cohesive set of responsibilities to an artificial class that does not represent anything in the problem domain, in order to support high cohesion, low coupling, and reuse.

Benefits:

High cohesion is supported because responsibilities are factored into a class that only focuses on a very specific set of related tasks.

Reuse potential may be increased because of the presence of fine grained Pure Fabrication classes.

Example

Suppose, in the point of sale example, that support is needed to save Sale instances in a relational database. By Expert, there is some justification to assign this responsibility to Sale class. However.

  • The task requires a relatively large number of supporting database-oriented operations and the Sale class becomes incohesive.
  • The sale class has to be coupled to the relational database increasing its coupling.
  • Saving objects in a relational database is a very general task for which many classes need support. Placing these responsibilities in the Sale class suggests there is going to be poor reuse or lots of duplication in other classes that do the same thing.  

 

Pure Fabrication : Example

PersistentStorageBroker

save()

By Pure Fabrication

  • The Sale remains well design, with high cohesion and low coupling
  • The PersistentStorageBroker class is itself relatively cohesive
  • The PersistentStorageBroker class is a very generic and reusable object

Example of Fabrication

• It is needed to save the Sale instances in a relational

database. By EXPERT, there is some justification that a

Sale knows how to save itself.

• Can Sale do this job?

Problems for Sale to do the job

• Large number of supporting database-oriented operations

will be attached to the Sale class.

• The Sale class becomes coupled with the RDB-interface,

so its coupling goes up.

• Saving an object is a very general task, many classes will

need this type of support.

– Placing these responsibilities in the Sale class will

result in poor reuse or duplication.

Pure Fabrication

  • Preserves low coupling and high cohesion of classes
  • Improve reusability of classes

Lessons from Fabrication

• A Pure Fabrication should be designed with high

potential for reuse.

– The responsibilities must remain small and

cohesive.

• It is partitioned on related functionality, and so is a

kind of function-centric object.

• Many existing object-oriented patterns are examples

of Pure Fabrication.

• High Cohesion is supported if functions are highly related

• Reuse potential should increase

• DANGER: may lead to function or process-oriented analysis

and design implemented in an OO language

– The spirit must remain object-centric

• there is a somebody in charge of this

Indirection

Problem:

To avoid direct coupling?

To de-couple objects so that Low coupling is supported and reuse potential remains high?

Solution:

Assign the responsibility to an intermediate object to mediate between other components or services, so that they are not directly coupled.

Example : PersistentStorageBroker

The Pure fabrication example of de-coupling the Sale from the relational database services through the introduction of a PersistentStorageBroker is also an example of assigning responsibilities to support Indirection. The PersistentStorageBroker acts as a intermediary between the Sale and database

Indirection : Example

CreditAuthorizationService

Modem

1:dial(phoneNum)

authorize(payment)

Assume that :

  • A point-of-sale terminal application needs to manipulate a modem in order to transmit credit payment request
  • The operating system provides a low-level function call API for doing so.
  • A class called CreditAuthorizationService is responsible for talking to the modem

If CreditAuthorizationService invokes the low –level API function calls directly, it is highly coupled to the API of the particular operating system. If the class needs to be ported to another operating system, then it will requiure modification.

Add an intermediate Modem class between the CreditAuthorizationService and the modem API. It is responsible for translating abstract modem requests to the API and creating an Indirection between the CreditAuthorizationService and the modem.

Indirection

  • Low coupling
  • Promotes reusability

Law of Demeter

Problem:

To avoid knowing about the structure of indirect objects?

Solution:

If two classes have no other reason to be directly aware of each other or otherwise coupled, then the two classes should not directly interact.

Law of Demeter

It states that within a method, messages should only be sent to the following objects:

  • The this object (or self)
  • A parameter of the method
  • An attribute of self
  • An element of a collection which is an attribute of self
  • An object created within the method

Law of Demeter : Example

In a point-of-sale application, assume that a Post instance has an attribute referring to a sale, which has an attribute referring to a payment.

Also,

  • Post instances support the paymentAmount operation, which returns the current amount tendered for the payment.
  • Sale instances support the payment operation, which returns the Payment instance associated with the sale.

Violates Law of Demeter : Example

The solution is a violation of this law because the POST instances is sending a message to an indirect object --- the Payment is not one of the five candidates ‘familiars’.

Support Law of demeter

The solution as the pattern suggests, is to add the responsibilityto the direct object – the sale in this case – to return the payment amount to the POST. This is known as promoting the interface, which is the general solution to support this principle. Therefore , a paymentAmount operation is added to sale so that the POST does not have to talk to a stranger.

Law of Demeter

  • Keeps coupling between classes low and makes a design more robust
  • Adds a small amount of overhead in the form of indirect method calls

Law of Demeter – Time totalling example

Time totalling example

Employee - Instances of the Employee class represent an employee.

PayrollRules – The rules for paying an employee vary with the laws that apply to the location where the employee works. Instances of the PayrollRules class encapsulate the pay rules that apply to an employee.

PayPeriod – Instances of the Payperiod class represent a range of days for which an employeee is paid in the same pay slip.

Shift – Instances of the Shift class represent ranges of time that the employee worked.

TimeTotaller – The Timetotaller class is an abstract class that the PayPeriod class uses to break the total hours worked during a pay period into normal and overtime minutes.

C1TimeTot,C2TimeTot,C3TimeTot – Concrete subclasses for different location of TimeTotaller that encapsulate the rules for breaking total minutes worked into normal and overtime minutes worked.

The following interaction must occur:

  • The pay period must become associated with an instance of the subclasss of TimeTotaller appropriate for the employee when the PayPeriod object is created.
  • The TimeTotaller object must be able to examine each shift in the pay period to learn the number of minutes worked in each shift.

Bad time-totalling collaboration

PayPeriod class has no reason to know anything about the PayrollRules class

For TimeTotaller to have direct access to the collection of shifts that it needs

implies violation of the Shift class’s encapsulation of how it aggregates

Collection of shifts -- resulting in higher level of coupling

Good time-totalling collaboration

To preserve the level of cohesion and coupling a less direct interaction may be used.

This is done as shown by the following collaboration diagram and the creation of additional methods.

Good time-totalling collaboration

Law of Demeter – Time totalling example with added operations

178.unknown

179.unknown

180.unknown

181.unknown

182.unknown

183.unknown

184.unknown

185.unknown

186.unknown

187.unknown

188.unknown

189.unknown

Sale

date

time

Sales

LineItem

quantity

Product

Specification

description

price

UPC

Described-

by

*

Contain

s

1..

*

Sale

date

time

total()

:Sale

t := total()

New method

Sale

date

time

total()

:Sale

t := total()

sli:SalesLineItem

SalesLineItem

quantity

subtotal()

2: st := subtotal()

:Product

Specification

2.1: p := price()

Product

Specification

description

price

UPC

price()

New method

SalesLineItem

:SalesLineItem

1*: [for each] sli := next()

Sale

date

time

makeLineItem()

total()

:Sale

makeLineItem(quantity)

:SalesLineItem

1: create(quantity)

New method

Payment

POST

Sale

:POST

p : Payment

:Sale

makePayment()

1: create()

2: addPayment(p)

:POST

:Sale

:Payment

makePayment()

1: makePayment()

1.1. create()

:POST

enterItem(upc, quantity)

:Store

enterItem(upc, quantity)

:Cashier

enterItem(upc, quantity)

:BuyItemsHandler

enterItem(upc, quantity)

Object Store

Enter Item

End Sale

UPC

Make Payment

Total

Quantity

Tendered

Balance

:POST

Cashier

:POSTCommand

presses button

onEnterItem()

1: enterItem(upc, qty)

:Sale

1.1: makeLineItem(upc, qty)

Presentation Layer

(Command Object)

Domain Layer

system event message

controller

Object Store

Enter Item

End Sale

UPC

Make Payment

Total

Quantity

Tendered

Balance

Cashier

:POSTCommand

presses button

onEnterItem()

:Sale

1: makeLineItem(upc, qty)

Presentation Layer

(Command object)

Domain Layer

It is undesirable for a presentation

layer objects such as a Java applet to

get involved in deciding how to handle

domain processes.

Business logic is embedded in the

presentation layer, which is not useful.

POSTApplet should not

send this message.

Modem

dial( )

receive( )

send( )

By Indirection

Modem::dial(phoneNum)

{

::OS_OpenPort(1);

::OS_Dial(phoneNUM)

}

POST

paymentAmount () : Float

endSale ()

enteritem ()

makePayment ()

1

1

Sale

date : Date

isComplete : Boolean

time : Time

becomeComplete ()

makeLineitem ()

makepayment ()

payment () : Payment

total () : Float

1

1

Payment

amountTendered

amountTendered () : Float

1

1

1

1

Captures

Paid-by

:Sale

1:prnt:=payment() : payment

:POST

prnt:Payment

1.1:amt:=amountTendered():Float

amt:=paymentAmount():Float

POST::PaymentAmount()

{

prnt:= m_sale->Payment()

//Violates Law of DM

return prnt->amountTendered();

}

Violates Law of DM

prnt is a 'Stranger' to

POST

1:prnt:=payment() : payment

1.1:amt:=amountTendered():Float

amt:=paymentAmount():Float

Supports the Law of

Demeter

:POST

prnt:Payment

:Sale

POST:: PaymentAmount()

{

return m_sale -> Payment();

Sale

date : Date

isComplete : Boolean

time : Time

becomeComplete( )

makeLineitem( )

makePayment( )

payment( )

paymentAmount( )

total( )

: System

enterItem

(id, quantity)

endSale()

makePayment

(amount)

Process Sale

1. Customer

arrives ...

2. Cashier

makes new

sale.

3. Cashier

enters item

identifier.

4....

Use Cases

System Sequence Diagrams

Operation: enterItem

Post-conditions:

- A

SalesLineItem

instance

sli

was created

-

. . .

Operation: makeNewSale

Post-conditions:

-

. . .

Contracts

make

NewSale()

: Cashier

Sale

date

. . .

Sales

LineItem

quantity

1..

*

1

. . .

. . .

domain objects

system

events

system

operations

the domain objects, attributes, and

associations that undergo state changes

Domain Model

Use-Case Model

some ideas and inspiration for the post-

conditions derive from the use cases

Design Model

: Register

enterItem

(itemID, quantity)

: ProductCatalog

spec := getSpecification( itemID )

addLineItem( spec, quantity )

: Sale

. . .

in addition to the use

cases, requirements that

must be satisfied by the

design of the software

use-case

realization

conceptual

classes in

the

domain

inspire the

names of

some

software

classes in

the design

makeNewSale()

create()

endSale()

. . .

. . .

Sample UP Artifact Relationships for Use-Case Realization

:Register

makeNewSale()

:Sale

create()

Register creates a

Sale by Creator

create()

:Sales

LineItem

by Creator, Sale

creates an empty

multiobject (such as

a List) which will

eventually hold

SalesLineItem

instances

CAUTION:

This is

not

a SalesLineItem instance. This is

a collection object (such as a List) that can

hold SalesLineitem objects.

by Creator

and

Controller

this activation is implied to be within the

constructor of the Sale instance

:Register

makeNewSale()

by Controller

1: makePayment(cashTendered)

1.1: create(cashTendered)

:Register

:Sale

:Payment

makePayment(cashTendered)

by Controller

by Creator and Low Coupling

:Register

endSale()

s :Sale

1: becomeComplete()

by Expert

by Controller

:Sale

tot := getTotal()

1 *: st := getSubtotal()

:ProductSpecification

1.1: pr := getPrice()

: SalesLineItem

*

by Expert

by Expert

recall this special notation to

indicate iteration over the

elements of a collection

1: makePayment(cashTendered)

1.1: create(cashTendered)

:Register

s :Sale

:Payment

makePayment(cashTendered)

:Store

2: addSale(s)

completedSales: Sale

completedSales: Sale

2.1: add(s)

by Expert

note that the Sale instance is named

's' so that it can be referenced as a

parameter in messages 2 and 2.1

2: makeLineItem(spec, qty)

enterItem(id, qty)

1: spec := getSpecification(id)

2.1: create(spec, qty)

1.1: spec := find(id)

:Register

:Sale

:Product

Catalog

sl: SalesLineItem

SalesLineItem

:SalesLineItem

:Product

Specification

2.2: add(sl)

by Expert

by Controller

This

find

message is to the

Map object (the multiobject),

not to a ProductSpecification.

CAUTION:

This is a multiobject collection (such as a Map), not a

ProductSpecification. It may contain many

ProductSpecifications.

CAUTION:

This is a multiobject collection (such as a List), not a

SalesLineItem. It may contain many SalesLineItems.

by Creator

add the newly created

SalesLineItem instance to the

multiobject (e.g., List)

:Register

:Sale

:CheckPayment

:DriversLicense

1.1: create(driversLicenseNum ,total)

1.2: authorize()

1:

makeCheckPayment(driversLicenseNum )

1.1.1:

create (driversLicenseNum )

makeCheckPayment(driversLicenseNum )

by Do It Myself and Polymorphism

by Creator

:Check

1.1.2:

create(total)

by Creator

:Register

:Sale

:CreditPayment

:CreditCard

1.1: create(ccNum,expiryDate,total)

1.2: authorize()

1:

makeCreditPayment(cardNum expiryDate)

1.1.1:

create (ccNum,expiryDate)

makeCreditPayment(ccNum,expiryDate)

by Creator

by Creator

by Do It Myself and Polymorphism

Store

...

addSale(s : Sale)

...

SalesLedger

...

addSale(s : Sale)

...

Store is responsible for

knowing and adding

completed Sales.

Acceptable in early

development cycles if the

Store has few

responsibilities.

SalesLedger is responsible

for knowing and adding

completed Sales.

Suitable when the design

grows and the Store

becomes uncohesive.

Sale

...

...

Sale

...

...

Logs-completed

5

Logs-completed

5

*

*

1

1

SalesLineItem

quantity : Integer

getSubtotal()

ProductCatalog

getSpecification()

ProductSpecification

description : Text

price : Money

itemID: ItemID

Store

address : Address

name : Text

addSale()

Payment

amount : Money

1..

*

1..

*

Register

endSale()

enterItem()

makeNewSale()

makePayment()

Sale

date : Date

isComplete : Boolean

time : Time

becomeComplete()

makeLineItem()

makePayment()

getTotal()

1

1

1

1

1

1

1

1

1

1

1

1

1

*

*

1