Class Design
Based on Chapter 14 of Bennett, McRobb
and Farmer:
Object Oriented Systems Analysis and
Design Using UML, (2nd Edition), McGraw
Hill, 2002.
03/12/2001 © Bennett, McRobb and Farmer 2002 1
In This Lecture You Will
Learn:
How to apply criteria for good design
How to design associations
The impact of integrity constraints on
design
How to design operations
The role of normalization in object
design
© Bennett, McRobb and Farmer 2002 2
Class Specification:
Attributes
An attribute’s data type is declared in UML using
the following syntax
name ‘:’ type-expression ‘=’ initial-value
‘{’property-string‘}’
Where
– name is the attribute name
– type-expression is its data type
– initial-value is the value the attribute is set to when the
object is first created
– property-string describes a property of the attribute, such
as constant or fixed
© Bennett, McRobb and Farmer 2002 3
Class Specification:
Attributes
BankAccount
Shows a accountNumber : Integer
derivable accountName : String {not null} BankAccount class
attribute
balance : Money = 0 with the attribute
/availableBalanc e : Money
overdraftLimit : Money
data types included
open(accountName : String) : Boolean
close() : Boolean
credit(amount:Money) : Boolean
debit(amount:Money) : Boolean
getBalance() : Money
setBalance(newBalance : Money)
getAccountName() : String
setAccountName(newName : String)
© Bennett, McRobb and Farmer 2002 4
Class Specification:
Attributes
The attribute balance in a BankAccount
class might be declared with an initial
value of zero using the syntax
balance: Money = 0.00
Attributes that may not be null are
specified
accountName: String {not null}
Arrays are specified
qualification[0..10]: String
© Bennett, McRobb and Farmer 2002 5
Class Specification:
Operations
The syntax used for an operation is
operation name ‘(’parameter-list ‘)’‘:’
return-type-expression
An operation’s signature is
determined by the operation’s
name, the number and type of its
parameters and the type of the
return value if any
© Bennett, McRobb and Farmer 2002 6
Class Specification:
Operations
BankAccount
accountNumber : Integer
accountName : String {not null}
balance : Money = 0
/availableBalanc e : Money
overdraftLimit : Money
open(accountName : String) : Boolean
close() : Boolean
credit(amount:Money) : Boolean
debit(amount:Money) : Boolean BankAccount class
getBalance() : Money with operation
setBalance(newBalance : Money)
getAccountName() : String signatures included.
setAccountName(newName : String)
© Bennett, McRobb and Farmer 2002 7
Which Operations?
Generally don’t show primary
operations
Only show constructors where they
have special significance
Varying levels of detail at different
stages in the development cycle
© Bennett, McRobb and Farmer 2002 8
Visibility
Visibility Visibility Meaning
symbol
Public The feature (an operation or an
+ attribute) is directly accessible by an
instance of any class.
Private The feature may only be used by an
- instance the class that includes it.
Protected The feature may be used either by the
# class that includes it or by a subclass
or decendant of that class.
Package The feature is directly accessible only
~ by instances of a class in the same
package.
© Bennett, McRobb and Farmer 2002 9
Visibility
BankAccount
- nextAccountNumber: Integer
- accountNumber: Integer
- accountName: String {not null}
- balance: Money = 0
BankAccount - /availableBalance: Money
class with - overdraftLimit: Money
visibility + open(accountName: String): Boolean
+ close(): Boolean
specified + credit(amount: Money): Boolean
+ debit(amount: Money): Boolean
+ viewBalance(): Money
# getBalance(): Money
- setBalance(newBalance: Money)
# getAccountName(): String
# setAccountName(newName: String)
© Bennett, McRobb and Farmer 2002 10
Interfaces
UML supports two notations to show
interfaces
– The small circle icon showing no detail
– A stereotyped class icon with a list of the
operations supported
– Normally only one of these notations is used on
any one diagram
The realize relationship, represented by the
dashed line with a triangular arrowhead,
indicates that the client class (e.g. Advert)
supports at least the operations listed in the
interface
© Bennett, McRobb and Farmer 2002 11
Interfaces Client
- companyName
for the CreativeStaff -
-
companyAddress
companyTelephone
- staffNo
Advert - staffName
-
-
companyFax
companyEmail
- staffStartDate
class - qualification
-
-
contactName
contactTelephone
- contactEmail
+ calculateBonus()
+ linkToNote() + assignStaffContact()
+ changeStaffContact()
«use»
«use»
Advert
- title
- type
- targetDate
- estimatedCost
- completionDate
Manageable Viewable
+ getCost()
+ setCompleted()
«realize» + view() «realize»
« interface»
Manageable « interface»
Viewable
+ getCost()
+ setCompleted() + view()
+ view() Realize
relationships
© Bennett, McRobb and Farmer 2002 12
Criteria for Good Design:
Coupling
Coupling describes the degree of
interconnectedness between
design components
It is reflected by the number of
links an object has and by the
degree of interaction the object
has with other objects
© Bennett, McRobb and Farmer 2002 13
Criteria for Good Design:
Cohesion
Cohesion is a measure of the degree to
which an element contributes to a single
purpose
The concepts of coupling and cohesion are
not mutually exclusive but actually support
each other
Coad and Yourdon (1991) suggested
several ways in which coupling and
cohesion can be applied within an object-
oriented approach
© Bennett, McRobb and Farmer 2002 14
Inheritance Coupling
Vehicle Poor inheritance
decription coupling as
Inheritance Coupling serviceDate unwanted
describes the degree maximumAltitude
takeOffSpeed attributes and
to which a subclass operations are
checkAltitude()
actually needs the takeOff() inherited
features it inherits
from its base class
LandVehicle
numberOfAxles
registrationDate
register()
© Bennett, McRobb and Farmer 2002 15
Operation Cohesion
Lecturer
lecturerName
lecturerAddress
roomNumber
roomLength
roomWidth {return
roomLenght*
calculateRoomSpace()
roomWidth;}
Good operation cohesion but poor class cohesion
© Bennett, McRobb and Farmer 2002 16
Poor Specialization
Cohesion
Address
number
street
town
Specialization
county Cohesion
country addresses the
postCode
semantic
cohesion of
inheritance
Person Company hierarchies
personName companyName
age annualIncome
gender annualProfit
© Bennett, McRobb and Farmer 2002 17
Improved Structure
Address
number
Improved street
structure town
county
using country
postCode
Address
class lives at is based at
Person Company
personName companyName
age annualIncome
gender annualProfit
© Bennett, McRobb and Farmer 2002 18
Liskov Substitution Principle
Essentially the principle states
that, in object interactions, it
should be possible to treat a
derived object as if it were a base
object without integrity problems
If the principle is not applied then
it may be possible to violate the
integrity of the derived object
© Bennett, McRobb and Farmer 2002 19
Liskov Substitution Principle
ChequeAccount
Account
Disinheritance accountName
accountName
balance
of debit() Restructuring
balance
means that the credit() to
debit() satisfy LSP credit()
left-hand
hierarchy is
not Liskov
compliant
MortgageAccount
MortgageAccount ChequeAccount
interestRate
interestRate
calculateInterest() debit()
- debit() calculateInterest()
© Bennett, McRobb and Farmer 2002 20
Further Design Guidelines
Design Clarity
Don’t Over-Design
Control Inheritance Hierarchies
Keep Messages and Operations Simple
Design Volatility
Evaluate by Scenario
Design by Delegation
Keep Classes Separate
© Bennett, McRobb and Farmer 2002 21
Designing Associations
Determine direction of message passing
—i.e. the navigability of the association
In general an association between two
classes A and B should be considered
with the questions
– Do objects of class A have to send
messages to objects of class B?
– Does an A object have to provide some
other object with B object identifiers?
If yes then A needs Bs object identifier
© Bennett, McRobb and Farmer 2002 22
Designing Associations
An association that has to support
message passing in both directions
is a two-way association
A two-way association is indicated
with arrowheads at both ends
Minimizing the number of two-way
associations keeps the coupling
between objects as low as possible
© Bennett, McRobb and Farmer 2002 23
Designing Associations
Arrowhead shows
the direction in
which messages can
be sent.
Owner
Car
- name : String -registrationNumber : Registration
- address : Address owns - make : String
- dateOfLicence : Date - model : String
1 1
-numberOfConviction : Integer
- colour : String
- ownedCar : Car
carObjectId
is placed in the
Owner class
One-way one-to-one association
© Bennett, McRobb and Farmer 2002 24
Fragment of
class manageCampaign
CreativeStaff
diagram for 1
- staffNo
the Agate workOnCampaign - staffName
- staffStartDate
case study *
1..* - qualification
+ calculateBonus()
Campaign + linkToNote()
*
- title Two-way
- campaignStartDate association
- campaignFinishDate 1
owns
- estimatedCost *
- completionDate
- datePaid Ad vert
- actualCost
- title
+ assignManager() One-way - type
+ assignStaff() association - targetDate
+ checkBudget() - estimatedCost
+ checkStaff()
- completionDate
+ completed()
+ getDuration()
+ getTeamMembers() + getCost()
+ setCompleted()
+ linkToNote()
+ listAdverts() + view()
+ recordPayment()
© Bennett, McRobb and Farmer 2002 25
One-to-many association
using a collection class.
Campaign
- title: String
- campaignStartDate: Date Ad vertCollection
- campaignFinishDate: Date
- estimatedCost: Money 1 has 1
- ownedAdvert: Ad vert [*]
- completionDate: Date
- datePaid: Date
- actualCost: Money + findFirst()
- ownedAdvertCollection: AdvertCollection + getNext()
+ addAdvert
+ assignManager() + removeAdvert()
+ assignStaff() 1
+ checkBudget()
+ checkStaff() owns
+ completed()
+ getDuration() *
+ getTeamMembers()
+ linkToNote()
+ listAdverts() Ad vert
+ recordPayment() - title: String
- type: String
- targetDate: Date
- estimatedCost: Money
- completionDate: Date
+ getCost()
© Bennett, McRobb and Farmer 2002 + setCompleted() 26
+ view()
Collection Classes
Collection classes are used to hold the
object identifiers when message passing
is required from one to many along an
association
OO languages provide support for these
requirements. Frequently the collection
class may be implemented as part of
the sending class (e.g. Campaign) as
some form of list
© Bennett, McRobb and Farmer 2002 27
Sequence diagram for
listAdverts()
:Campaign :AdvertCollection :Advert
This sequence listAdverts()
advert = findFirst()
diagram
advertTitle = getTitle()
shows the
interaction [until no more adverts] advert = *getNext()
when using a loop
collection advertTitle = getTitle()
class end loop
© Bennett, McRobb and Farmer 2002 28
Two-way Many-to-many
Associations
CreativeStaff 1 StaffCollection
* workOn
- staffCampaigns: CampaignCollection - campaignStaff: Staff [*]
+ listCampaigns() + findFirst()
+ getNext()
1 + addStaff()
has + removeStaff()
+ findStaff()
has
1 1
CampaignCollection Campaign
1 *
- staffCampaign: Campaign [*] - staffCollection: StaffCollection
workOn
+ findFirst() + listStaff()
+ getNext()
+ addCampaign()
+ removeCampaign()
This is the design for the
+ findCampaign() works On Campaign
© association
Bennett, McRobb and Farmer 2002 29
Integrity Constraints
Referential Integrity that ensures that
an object identifier in an object is
actually referring to an object that exists
Dependency Constraints that ensures
that attribute dependencies, where one
attribute may be calculated from other
attributes, are maintained consistently
Domain Integrity that ensures that
attributes only hold permissible values
© Bennett, McRobb and Farmer 2002 30
Constraints Between
Associations
* isAMemberOf
*
Committee
Employee
memberCollection[*] {subset}
committeeChair
assignChair()
isChairOf 0..1
*
© Bennett, McRobb and Farmer 2002 31
Designing Operations
Various factors constrain algorithm
design:
– the cost of implementation
– performance constraints
– requirements for accuracy
– the capabilities of the implementation
platform
© Bennett, McRobb and Farmer 2002 32
Designing Operations
Factors that should be considered
when choosing among alternative
algorithm designs
– Computational complexity
– Ease of implementation and
understandability
– Flexibility
– Fine-tuning the object model
© Bennett, McRobb and Farmer 2002 33
Normalisation
Normalization may be useful in OO
approaches
– when using a relational database
management
– as a guide to decomposing a large,
complex (and probably not very
cohesive) objects
Objects need not be normalised but
it is important to remove redundancy
© Bennett, McRobb and Farmer 2002 34
Summary
In this lecture you have learned
about:
how to apply criteria for good design
how to design associations
the impact of integrity constraints on
design
how to design operations
the role of normalization in object
design
© Bennett, McRobb and Farmer 2002 35
Designing Boundary
Classes
Based on Chapter 17 of Bennett, McRobb
and Farmer:
Object Oriented Systems Analysis and
Design Using UML, (2nd Edition), McGraw
Hill, 2002.
03/12/2001 © Bennett, McRobb and Farmer 2002 36
In This Lecture You Will
Learn:
What we mean by the presentation layer
How prototyping can be applied to user
interface design
How to add boundary classes to the
class model
How to model boundary classes in
sequence diagrams
How design patterns can be applied to
the user interface
How to model control using statecharts
© Bennett, McRobb and Farmer 2002 37
Architecture of the
Presentation Layer
We aim to separate the classes that
have the responsibility for the
interface with the user, or with other
systems, (boundary classes) from
the business classes (entity classes)
and the classes that handle the
application logic (control classes)
This is the Three-Tier Architecture
© Bennett, McRobb and Farmer 2002 38
Presentation Layer
Handles interface with users and other
systems
Formats and presents data at the interface
Presentation can be for display as text or
charts, printing on a printer, speech
synthesis, or formatting in XML to transfer
to another system
Provides a mechanism for data entry by
the user, but the events are handled by
control classes
© Bennett, McRobb and Farmer 2002 39
Presentation Layer
Does not contain business classes—
Clients, Campaigns, Adverts,
Invoices, Staff etc.
Does not contain the business logic—
rules like ‘A Campaign must have one
and only one Campaign Manager’.
Doesn’t handle validation, beyond
perhaps simple checks on formatting
© Bennett, McRobb and Farmer 2002 40
Reasons for the
3-Tier Architecture
Logical design
The project team may be producing analysis and design models that are
independent of the hardware and software environment in which they are to be
implemented. For this reason, the entity classes, which provide the functionality
of the application, will not include details of how they will be displayed.
Interface independence
Even if display methods could be added to classes in the application, it would not
make sense to do so. Object instances of any one class will be used in many
different use cases: sometimes their attributes will be displayed on screen,
sometimes printed by a printer. There will not necessarily be any standard layout
of the attributes that can be built into the class definition, so presentation of the
attributes is usually handled by another class.
Reuse
One of the aims is to produce classes that can be reused in different applications.
For this to be possible, the classes should not be tied to a particular
implementation environment or to a particular way of displaying the attribute
values of instances.
© Bennett, McRobb and Farmer 2002 41
3-Tier Architecture
Different authors have used
different terms
– Boundary , Entity, Control
– Model, View, Controller
– Human Interaction Component,
Problem Domain Component, Task
Management Component
(not necessarily in the same order)
© Bennett, McRobb and Farmer 2002 42
Developing Boundary
Classes
Prototype the user interface
Design the classes
Model the interaction involved in
the interface
Model the control of the interface
using statechart diagrams (if
necessary)
© Bennett, McRobb and Farmer 2002 43
Prototyping the User
Interface
A prototype is a model that looks,
and partly behaves, like the finished
product but lacks certain features
A prototype of the user interface is a
horizontal prototype—it prototypes
one layer of the system
A vertical prototype takes a sub-
system and prototypes all the layers
© Bennett, McRobb and Farmer 2002 44
Prototyping the User
Interface
Distinction between
– prototypes developed in an iterative
process that are elaborated to
become part of the eventual system
and
– prototypes developed to test out
design ideas that are thrown away
rather than being further enhanced
(actually, they are not really thrown
away, as they form part of the design)
© Bennett, McRobb and Farmer 2002 45
Check Campaign Budget
Use Case Prototype
In this prototype, Clients and Campaigns
are selected in drop-down lists
There are other ways…
© Bennett, McRobb and Farmer 2002 46
Check Campaign Budget
Use Case Prototype
Using a treeview control…
© Bennett, McRobb and Farmer 2002 47
Check Campaign Budget
Use Case Prototype
Using a separate look-up window
© Bennett, McRobb and Farmer 2002 48
Check campaign budget
Use Case Prototype
Choice of approach is part of the style
guidelines discussed in Chapter 16
We are going to use the first approach,
with drop-down lists
Although in Chapter 6, we looked at use
cases for ‘Find campaign’, ‘Find client’
etc. as separate look-up windows, this
approach is not what the Agate users
want
© Bennett, McRobb and Farmer 2002 49
Designing Classes
Start with the collaborations from the
analysis model
Elaborate the collaborations to include
necessary boundary, entity and control
classes
Rosenberg and Scott (1999) treat control
classes as placeholders—they represent
some responsibility that has to be handled
somewhere, but it may become an
operation of another class
© Bennett, McRobb and Farmer 2002 50
Collaboration for
Check campaign budget
Check Campaign Check Campaign Campaign Advert
Budget UI Budget
In order to find the right Campaign, we
also need to use the Client class, even
though it doesn’t participate in the real
process of checking the budget
We also add control classes for the
respons-ibilities of listing clients and
campaigns
© Bennett, McRobb and Farmer 2002 51
Collaboration for
Check campaign budget
List Clients Client
Check Check Campaign Advert
Campaign Campaign
Budget UI Budget
List
Campaigns
© Bennett, McRobb and Farmer 2002 52
Alternative Collaboration for
Check campaign budget
List Clients UI List Clients Client
Check Campaign Check Campaign Campaign Advert
Budget UI Budget
List Campaigns List Campaigns
UI
© Bennett, McRobb and Farmer 2002 53
Class Diagram for
CheckCampaignBudgetUI
Dialog
CheckCampaignBudgetUI
1 1 1 1
3 2 1 2
Label Button TextField Choice
© Bennett, McRobb and Farmer 2002 54
Single Class for
CheckCampaignBudgetUI
Draw in your own lines to show
which attribute is which element of
the interface CheckCampaignBudgetUI
- clientLabel : Label
- campaignLabel : Label
- budgetLabel : Label
- checkButton : Button
- closeButton : Button
- budgetTextField : TextField
- clientChoice : Choice
- campaignChoice : Choice
© Bennett, McRobb and Farmer 2002 55
Package Dependencies
Classes can be shown with
package namesAWT::Dialog
CheckCampaignBudgetUI
1 1 1 1
3 2 1 2
AWT::Label AWT::Button AWT::TextField AWT::Choice
© Bennett, McRobb and Farmer 2002 56
Package Dependencies
There is an «import» dependency
between the two packages
import [Link].*; // In Java
using [Link]; // in C#
AWT Agate User
«import»
Interface
© Bennett, McRobb and Farmer 2002 57
Sequence Diagrams
:Client :Campaign :Advert
Campaign
Manager
getName( )
listCampaigns( )
*getCampaignDetails( )
checkCampaignBudget( ) *getCost( )
getOverheads( )
© Bennett, McRobb and Farmer 2002 58
Sequence Diagrams
The sequence diagram on the
previous slide just shows the entity
classes
We also have the collaboration
diagram from an earlier slide showing
the control and boundary classes
We now need to model the
interaction more detail
© Bennett, McRobb and Farmer 2002 59
First Part of Sequence
Diagram
Campaign
Manager :CheckCampaign
CheckCampaignBudget( ) Budget
ccbUI := Check
:CheckCampaign Campaign
BudgetUI BudgetUI( this )
:ListClients
lc := ListClients( )
listAllClients( ccbUI )
*addClientName( name )
enable( )
© Bennett, McRobb and Farmer 2002 60
First Part of Sequence
Diagram
The control class
– creates the instance of the boundary class
– creates the instance of the ListClients
control class
– passes to :ListClients a reference to the
boundary class
– :ListClients then sets the name of each
client in turn into the boundary class by
calling addClientname(name) repeatedly
© Bennett, McRobb and Farmer 2002 61
Using Interfaces
We don’t mean user interfaces!
Many boundary classes will need to list
clients to allow the user to select a client
The ListClients control class doesn’t
need to know how the boundary class
lists them
The boundary class needs to implement
the ClientLister interface and provide
an implementation of the operation
addClientName(String)
© Bennett, McRobb and Farmer 2002 62
Using Interfaces
CheckCampaignBudgetUI
«interface»
ClientLister - clientLabel : Label
- campaignLabel : Label
+ addClientName(String) - budgetLabel : Label
- checkButton : Button
«use» - closeButton : Button
- budgetTextField : TextField
- clientChoice : Choice
ListClients - campaignChoice : Choice
+ listAllClients(ClientLister) + enable( )
Attributes can be private, only accessed
through the public interface
© Bennett, McRobb and Farmer 2002 63
Java Implementation
import [Link].*;
public class CheckCampaignBudgetUI extends
Frame implements ClientLister
{
private Choice clientChoice;
...
public void addClientName(String name) {
[Link](name);
}
...
}
© Bennett, McRobb and Farmer 2002 64
listAllClients( ) Operation
:ListClients :Client cl:ClientLister
:ClientLister
listAllClients( cl )
aClient := getNextClient( )
name := getName( )
addClientName( name )
* [ while more clients ]
© Bennett, McRobb and Farmer 2002 65
Second Part
of Sequence Diagram
Campaign
Manager :CheckCampaign :CheckCampaign
BudgetUI Budget
select client
clientSelected( )
aClient := getSelectedClient( )
:ListCampaigns
lc := ListCampaigns( )
listCampaigns( ccbUI, aClient )
*addCampaignName( name )
© Bennett, McRobb and Farmer 2002 66
Event-driven User Interface
Event in :clientChoice is passed
through to the main boundary
class
Campaign
Manager clientChoice :CheckCampaign :CheckCampaign
:Choice BudgetUI Budget
select client itemState [[Link] =
Changed( evt ) clientChoice]
clientSelected( )
© Bennett, McRobb and Farmer 2002 67
Revised Second Part
of Sequence Diagram
Campaign
Manager :CheckCampaign :CheckCampaign
BudgetUI Budget
select client
clientSelected( )
aClient := getSelectedClient( )
:ListCampaigns
lc := ListCampaigns( )
clearAllCampaignNames( )
listCampaigns( ccbUI, aClient )
*addCampaignName( name )
© Bennett, McRobb and Farmer 2002 68
Final Part
of Sequence Diagram
Campaign
Manager :CheckCampaign :CheckCampaign
:Campaign :Advert
BudgetUI Budget
select campaign
campaignSelected( )
enableCheckButton( )
check budget
checkCampaignBudget( )
getCampaignSelected( )
checkCampaignBudget( )
*getCost( )
getOverheads( )
setBudget( )
© Bennett, McRobb and Farmer 2002 69
Adding to the Class Diagram
From the sequence diagrams, we can see
that the CheckCampaignBudgetUI class
needs to implement both the
ClientLister and the CampaignLister
interfaces
There are also additional operations that
have been introduced, some of which will
apply to any class that implements these
interfaces (and therefore belong to the
interfaces), and some of which belong to
the CheckCampaignBudgetUI class
© Bennett, McRobb and Farmer 2002 70
ListCampaigns «interface»
java::awt::event::ItemListener
+ listAllCampaigns(CampaignLister)
+ listCampaigns(CampaignLister, Client) + itemStateChanged(ItemEvent evt)
«use»
«interface»
CampaignLister
+ addCampaignName(String) CheckCampaignBudgetUI
+ clearAllCampaignNames( )
+ removeCampaignName(String) - clientLabel : Label
- campaignLabel : Label
«interface» - budgetLabel : Label
ClientLister - checkButton : Button
- closeButton : Button
+ addClientName(String) - budgetTextField : TextField
+ clearAllClientNames( ) - clientChoice : Choice
+ removeClientName(String) - campaignChoice : Choice
«use» + enable( )
+ enableCheckButton( )
ListClients + getSelectedClient( )
+ getSelectedCampaign( )
+ listAllClients(ClientLister) + setBudget(Currency)
© Bennett, McRobb and Farmer 2002 71
Using Design Patterns
More and more, libraries of classes are
built around design patterns
In Smalltalk, the Model–View–Controller
architecture is widely used
In Java, an approach is used in which
objects register an interest in events,
then when an event occurs all the
objects that have registered are notified
of the event
© Bennett, McRobb and Farmer 2002 72
Model–View–Controller
6: Update Presentation
User E vent
/Controller
:Controller :View
/View
1: Notify Change
5: Notify Change
6: Request Model Dat a
4: Request Model Dat a
2: Update self
/Model
:Model
3: Notify Change
© Bennett, McRobb and Farmer 2002 73
Java Listener Approach
4 Update Self
User Event
:Component :any:Class
1: itemStateChanged
(ItemEvent evt)
:ItemListener
2: Inspect Event
3: [Event of Interest]
Notify Class of Event
© Bennett, McRobb and Farmer 2002 74
Java Approach
Various listeners for different kinds
of user interface components
– MouseListener
– ItemListener
– ActionListener
All subinterfaces of EventListener
© Bennett, McRobb and Farmer 2002 75
Java2 Enterprise
Edition (J2EE) Approach
J2EE is used for N-Tier distributed
systems based on Enterprise Java
Beans (EJB)
J2EE Core Patterns provides a
pattern catalogue that uses the
Model–View–Controller architecture
© Bennett, McRobb and Farmer 2002 76
Modelling the User Interface
in Statechart Diagrams
Different approaches to using
statecharts
– Browne (1994), which was used in the
1st edition
– Horrocks (1999) used here
– Both based on the original work of
Harel (1987)
– Recent work of Harel and Politi (1998)
© Bennett, McRobb and Farmer 2002 77
Horrocks’ Approach
Five tasks:
– describe the high-level requirements
and main user tasks
– describe the user interface behaviour
– define user interface rules
– draw the statechart (and successively
refine it)
– prepare an event action table
© Bennett, McRobb and Farmer 2002 78
High-level Requirements
The requirement here is that the users
must be able to check whether the budget
for an advertising campaign has been
exceeded or not. This is calculated by
summing the cost of all the adverts in a
campaign, adding a percentage for
overheads and subtracting the result from
the planned budget. A negative value
indicates that the budget has been
overspent. This information is used by a
campaign manager.
© Bennett, McRobb and Farmer 2002 79
User Interface Behaviour
The client dropdown displays a list of clients. When
a client is selected, their campaigns will be displayed
in the campaign dropdown.
The campaign dropdown displays a list of
campaigns belonging to the client selected in the
client dropdown. When a campaign is selected the
check button is enabled.
The budget textfield displays the result of the
calculation to check the budget.
The check button causes the calculation of the
budget balance to take place.
The close button closes the window and exits the
use case. © Bennett, McRobb and Farmer 2002
80
Define User Interface Rules
User interface objects with constant
behaviour
– The client dropdown has constant behaviour.
Whenever a client is selected, a list of
campaigns is loaded into the campaign
dropdown
– The budget textfield is initially empty. It is
cleared whenever a new client is selected or a
new campaign is selected. It is not editable
– The close button may be pressed at any time to
close the window
© Bennett, McRobb and Farmer 2002 81
Define User Interface Rules
User interface objects with varying
behaviour
– The campaign dropdown is initially disabled.
No campaign can be selected until a client
has been selected. Once it has been loaded
with a list of campaigns it is enabled
– The check button is initially disabled. It is
enabled when a campaign is selected. It is
disabled whenever a new client is selected
© Bennett, McRobb and Farmer 2002 82
Define User Interface Rules
Entry and exit events
– The window is entered from the main window
when the Check Campaign Budget menu
item is selected
– When the close button is clicked, an alert
dialogue is displayed. This asks ‘Close
window? Are you sure?’ and displays two
buttons labelled ‘OK’ and ‘Cancel’. If ‘OK’ is
clicked the window is exited; if ‘Cancel’ is
clicked then it carries on in the state it was in
before the close button was clicked
© Bennett, McRobb and Farmer 2002 83
Draw the Statechart
We start with the top-level
statechart for movement between
the windows and dialogues
Main Window
checkCampaignBudget
MenuSelected( )
‘OK’
closeButtonClicked( )
Check Budget
Alert Dialogue
Window
‘Cancel’
© Bennett, McRobb and Farmer 2002 84
Draw the Statechart
Client selection states are nested
within the Check Budget Window
state
clientSelected( )
No Client
Client Selected
Selected
clientSelected( )
© Bennett, McRobb and Farmer 2002 85
Draw the Statechart
Campaign selection states are
nested within the Client
Selected state
campaignSelected( )
No Campaign Campaign
Selected Selected
campaignSelected( )
© Bennett, McRobb and Farmer 2002 86
Draw the Statechart
Display of result states are nested
within Campaign Selected state
checkButtonPressed( )
Display
Blank
Result
checkButtonPressed( )
© Bennett, McRobb and Farmer 2002 87
‘OK’ ‘Cancel’
Main Window 7 Alert Dialogue
checkCampaignBudget
closeButtonClicked( )
MenuSelected( )
Check Budget Window
H*
1 No Client
Selected
clientSelected( )
clientSelected( )
2 Client Selected
3 No Campaign
Selected
campaignSelected( )
campaignSelected( )
4 Campaign Selected
checkButtonPressed( )
6 Display
5 Blank
Result
checkButtonPressed( )
© Bennett, McRobb and Farmer 2002 88
Draw the Statechart
Non-UML features:
– Horrocks numbers the states
– State variables can be shown in square
brackets
Statechart can be simplified (as on next
slide)
Rather than try to add all messages
associated with transitions into the
diagram, an Event–Action table can be
used
© Bennett, McRobb and Farmer 2002 89
‘OK’ ‘Cancel’
Main Window 5 Alert Dialogue
checkCampaignBudget
closeButtonClicked( )
MenuSelected( )
Check Budget Window
H*
1 No Client
Selected
clientSelected( )
clientSelected( )
2 No Campaign
Selected
campaignSelected( )
campaignSelected( )
checkButtonPressed( )
4 Display
3 Blank
Result
checkButtonPressed( )
© Bennett, McRobb and Farmer 2002 90
Event–Action Table
© Bennett, McRobb and Farmer 2002 91
Revising the Sequence
Diagrams and Class
Diagrams
Producing the statechart diagram and
the event–action table has identified
some additional messages that will be
sent to the user interface to control it
These will need to be added to the
sequence diagrams and to the class
diagram as operations of the UI class
or of the lister interfaces
© Bennett, McRobb and Farmer 2002 92
Revised First Sequence
Diagram
Campaign
Manager :CheckCampaign
CheckCampaignBudget( ) Budget
ccbUI := Check
:CheckCampaign Campaign
BudgetUI BudgetUI( this )
:ListClients
lc := ListClients( )
listAllClients( ccbUI )
*addClientName( name )
enable( )
disableCampaignList( )
disableCheckButton( )
© Bennett, McRobb and Farmer 2002 93
Summary
In this lecture you have learned about:
What we mean by the presentation layer
How prototyping can be applied to user
interface design
How to add boundary classes to the class
model
How to model boundary classes in sequence
diagrams
How design patterns can be applied to the
user interface
How to model control using statecharts
© Bennett, McRobb and Farmer 2002 94