introduction to object oriented design.pdf
TRANSCRIPT
-
7/30/2019 Introduction to Object Oriented Design.pdf
1/87
Introduction to ObjectOriented Design
-
7/30/2019 Introduction to Object Oriented Design.pdf
2/87
Analysis Phase Revisited
Defining use cases
Use case diagram
System sequence diagram
Conceptual Model (Analysis ClassDiagram)
CRC Cards
Operation Contracts State Diagrams
-
7/30/2019 Introduction to Object Oriented Design.pdf
3/87
What are the system events andoperations?
System SequenceDiagram
What do the system operations do?Contracts
What are the concepts and terms?Conceptual Model(Analysis ClassDiagram)
What are the domain processes?Use Cases
Questions AnsweredAnalysis Artifact
-
7/30/2019 Introduction to Object Oriented Design.pdf
4/87
Activities Carried out in OOD Develop real use cases
Drawing interaction diagrams Sequence / collaboration diagrams
Assigning responsibility to objects
Grasp Patterns GoF Patterns
Determining visibility
Drawing design class diagrams Deciding on architectural issues
Logical Architecture and UML Package Diagram
-
7/30/2019 Introduction to Object Oriented Design.pdf
5/87
Logical Architecture, Layers and partitions
The logical architecture is the large scale organization of thesoftware classes into packages (or namespace), subsystems andlayers. It is called logical architecture because at this stage there is no decision
about how these elements are deployed across different operatingsystems processes or across physical computers in the network.
A layer is a very coarse grained grouping of classes, packages, orsubsystems that has cohesive responsibility for the major part of the
system
Typical layers in an OO system includes User interface Application logic and domain objects
Technical service The layers of an architecture represent vertical slices, while
partitions represent a horizontal division of the relatively parallelsubsystems of a layer.
-
7/30/2019 Introduction to Object Oriented Design.pdf
6/87
Model View Separation Principle
MVS Principle states that model objects
should not have direct knowledge of viewobjects (User Interface).
-
7/30/2019 Introduction to Object Oriented Design.pdf
7/87
Relationship between SSD andLayers
SSD illustrates specific system operation
but hide specific UI layer of the systemthat captures this system operationrequests.
UI objects actually delegates theserequests to the domain layer for handing.
-
7/30/2019 Introduction to Object Oriented Design.pdf
8/87
Domain
UI
Swing
ProcessSaleFrame
...
... Register
makeNewSale()enterItem()...
: Cashier
makeNewSale()enterItem()endSale()
makeNewSale()enterItem()endSale()
enterItem(id, quantity)
:System
Cashier
endSale()
description, total
makeNewSale()
the system operations handled by the system in an SSD represent theoperation calls on the Application or Domain layer from the UI layer
-
7/30/2019 Introduction to Object Oriented Design.pdf
9/87
Domain
UI
Swingnot the JavaSwing libraries, butour GUI classes
based on Swing
Web
Sales Payments Taxes
Technical Services
Persistence Logging RulesEngine
VerticalLayers
Horizontal Partitions
An UML Package Diagram
-
7/30/2019 Introduction to Object Oriented Design.pdf
10/87
Developing Real Use cases
A real use case describe the real or actual
design of the use case in terms ofconcrete input and output technology andits over all implementation
Diagrams, story boards,
Interface widgets (window objects)
-
7/30/2019 Introduction to Object Oriented Design.pdf
11/87
Widget for the Enter Item System Eventunder Process Sale use case
-
7/30/2019 Introduction to Object Oriented Design.pdf
12/87
:Register
Cashier
:ProcessSaleJFrame
actionPerformed( actionEvent )
1: enterItem(id, qty)system event
UI
Layer
Domain
Layer
presses button
Connecting User Interface (View)and Domain Layer (Model)
-
7/30/2019 Introduction to Object Oriented Design.pdf
13/87
:Register
Cashier
:ProcessSaleJFrame
actionPerformed( actionEvent )
1: enterItem(id, qty)
2 [no sale] : s = getSale : Sale
UI
Layer
DomainLayer
s : Sale
3: t = getTotal
presses button
Connecting User Interface (View)and Domain Layer (Model)
-
7/30/2019 Introduction to Object Oriented Design.pdf
14/87
Drawing Interaction Diagrams Interaction Diagrams
Collaboration diagrams Sequence diagrams
Drawn on the basis of conceptual model(analysis class diagram)
Show the choices in assigning responsibility toobjects
Decision for assigning the responsibilities arebased on the flow of massages between theinteracting objects.
Use of patterns
-
7/30/2019 Introduction to Object Oriented Design.pdf
15/87
Responsibilities and Methods Responsibility is defined as a contract or obligation of a
type or a class
Responsibilities are related to the obligations of anobject in terms of its behaviour
Two types of responsibility Doing
Doing something itself Initiating action in other objects Controlling or coordinating the activities in other objects
Knowing Knowing about private encapsulated data
Knowing about related objects Knowing about the things it can derive or calculate
Ex: Sale is responsible for printing itself (doing)Sale is responsible for knowing its date
-
7/30/2019 Introduction to Object Oriented Design.pdf
16/87
: Register : Sale
makePayment(cashTendered)
makePayment(cashTendered)
: Paymentcreate(cashTendered)
1: makePayment(cashTendered)
1.1: create(cashTendered)
:Register :Sale
:Payment
makePayment(cashTendered)
direction of message
Sequence Diagram
Collaboration Diagram
-
7/30/2019 Introduction to Object Oriented Design.pdf
17/87
What are Design Patterns A design pattern is usually defined as a
common solution to a recurring problem in agiven context. It specifies the structure and behaviour of a
society of classes
Usually presented as a problem and solutionpair
Never convey a new idea
have a name for ease of communication Grasp patterns (Larman) GoF Patterns (Gamma et al.)
-
7/30/2019 Introduction to Object Oriented Design.pdf
18/87
Grasp Patterns
(Five basic patterns)
Creator
Information Expert
High Cohesion
Low Coupling Controller
-
7/30/2019 Introduction to Object Oriented Design.pdf
19/87
Creator
Problem: Who should be responsible forcreating a new instance of some class?
Solution: Assign class B the responsibility tocreate an instance of class A if one of thefollowing is true
B aggregates A objects (Whole-part relationship) B Contains A objects
B records instances of A objects
B closely uses A objects B has the initializing data that will be passed to A
when it is created (B is an expert with respect to A)
-
7/30/2019 Introduction to Object Oriented Design.pdf
20/87
Sale
date
time
SalesLineItem
quantity
Product Spec
description
pricecode
1..*
Contains
described by
Partial Conceptual Model
1
*
1Sale aggregates manySalesLineItemobjects. CreatePattern suggest that sale is a
good candidate to have theresponsibility of creating it
-
7/30/2019 Introduction to Object Oriented Design.pdf
21/87
: Sale
sli: SaleLineItem
Sale
datetime
total()MakeLineItem()
SalesLineItem
quantity
subtotal()
MakeLineItem(quantity)
1: Create(quantity)
: Register
-
7/30/2019 Introduction to Object Oriented Design.pdf
22/87
Information Expert Problem: What is a general principle of
assigning responsibilities to objects? Solution: Assign the responsibility to the
information expert- the class that hasinformation necessary to fulfill theresponsibility.
-
7/30/2019 Introduction to Object Oriented Design.pdf
23/87
Partial Conceptual ModelSale
time
SalesLineItem
quantity
ProductDescription
descriptionpriceitemID
Described-by*
Contains
1..*
1
1
-
7/30/2019 Introduction to Object Oriented Design.pdf
24/87
Sale
time
...
getTotal()
:Salet = getTotal
New method
-
7/30/2019 Introduction to Object Oriented Design.pdf
25/87
Sale
time
...
getTotal()
SalesLineItem
quantity
getSubtotal()New method
1 *: st = getSubtotal: Salet = getTotallineItems[ i ] :
SalesLineItem
this notation will imply we
are iterating over all
elements of a collection
-
7/30/2019 Introduction to Object Oriented Design.pdf
26/87
Sale
time...
getTotal()
SalesLineItem
quantity
getSubtotal()
Product
Description
description
price
itemID
getPrice ()New method
:Product
Description
1.1: p := getPrice()
1 *: st = getSubtotal: Sale
t = getTotal lineItems[ i ] :
SalesLineItem
Knows product priceProductDescription
Knows line item sub totalSalesLineItem
Knows Sales TotalSaleResponsibilityClass
-
7/30/2019 Introduction to Object Oriented Design.pdf
27/87
Low Coupling
Problem: How to support low dependencyand increase reuse?
Solution: assign a responsibility so thatcoupling remains low.
A class with weak coupling does not dependon too many other classes
-
7/30/2019 Introduction to Object Oriented Design.pdf
28/87
: Register
p : payment
:Sale
1: create()
makePayment()
2: addPayment(p)
: Register p : payment
:Sale
1: makePayment()
makePayment()
1.1:create()
Design 1
Design 2(Low Coupling)
-
7/30/2019 Introduction to Object Oriented Design.pdf
29/87
High Cohesion Problem: How to keep objects focused,
understandable, and manageable, and asa side effect, support Low Coupling?
Solution: Assign a responsibility so thatcohesion remains high. Use this toevaluate alternatives.
-
7/30/2019 Introduction to Object Oriented Design.pdf
30/87
Controller What first object beyond the UI layer receives
and coordinates (controls) system operation? Assign the responsibility for handling a system
event to a class representing one of thefollowing choices Represents the overall system (Faade Controller) Represents over all business organization (Faade
controller) Represents something in the real world that is active
(For example, the role of a person) that might beinvolved in the task (role controller)
Represents an artificial handler of all system eventsof a use case (use case/session controller)
System Operations: Major input event generatedby external actor
Controller: is a non-user interface object
responsible for handling a system event
-
7/30/2019 Introduction to Object Oriented Design.pdf
31/87
Which class of object should be responsible for receiving thissystem event message?
It is sometimes called the controller or coordinator. It does notnormally do the work, but delegates it to other objects.
The controller is a kind of "facade" onto the domain layer fromthe interface layer.
actionPerformed( actionEvent )
: ???
: Cashier
:SaleJFrame
presses button
enterItem(itemID, qty)
UI Layer
DomainLayer
system operation message
-
7/30/2019 Introduction to Object Oriented Design.pdf
32/87
Choices for Controller:
Represents overall system : Register, POSSystem Facade Controller: Few system events
Represents the business organization : Store Facade Controller: Few system events
Represents something active in the real-world: Cashier Roll controller: All the responsibilities of a single real-world object
Artificial handler of a use case containing the systemoperation : ProcessSaleHandler UseCase Controller: Too many system events
Choice of the most appropriate controller depends on thefactors like cohesion and coupling.
-
7/30/2019 Introduction to Object Oriented Design.pdf
33/87
:RegisterenterItem(id, quantity)
:ProcessSaleHandlerenterItem(id, quantity)
-
7/30/2019 Introduction to Object Oriented Design.pdf
34/87
Register
...
endSale ()
enterItem ()
makeNewSale ()
makePayment ()
makeNewReturn ()
enterReturnItem (). . .
System
endSale ()
enterItem ()
makeNewSale ()
makePayment ()
makeNewReturn ()
enterReturnItem ()
. . .
system operations
discovered during system
behavior analysis
allocation of system
operations during design ,
using one facade controller
-
7/30/2019 Introduction to Object Oriented Design.pdf
35/87
ProcessSale
Handler
...
endSale ()
enterItem ()makeNewSale()
makePayment()
System
endSale ()
enterItem ()
makeNewSale()
makePayment()
enterReturnItem()
makeNewReturn()
. . .
allocation of system
operations during design,
using several use case
controllers
HandleReturns
Handler
...
enterReturnItem ()
makeNewReturn (). . .
-
7/30/2019 Introduction to Object Oriented Design.pdf
36/87
Bloated Controller A Controller handling too many responsibilities
(Low Cohesion) Sign of Bloated Controller A single controller receiving all system events,
Low cohesion
Too many attributes
Solution More controller
Single controller that delegates the responsibility toother objects
-
7/30/2019 Introduction to Object Oriented Design.pdf
37/87
enterIteminteraction diagram
(Dynamic View)
2: makeLineItem(desc, qty)enterItem(id, qty)
1: desc = getProductDesc(id) 2.1: create(desc, qty)
1.1: desc = get(id)
:Register :Sale
:ProductCatalog
sl: SalesLineItem
lineItems :List
: Map
2.2: add(sl)
by Expert
by Controllerby Creator
add the newly created
SalesLineItem instance to the List
-
7/30/2019 Introduction to Object Oriented Design.pdf
38/87
Partial Design Class Diagram (DCD)
related to enterItemdesign
SalesLineItem
quantity : Integer
...
ProductCatalog
...
getProductDesc(...)
ProductDescription
description : Textprice : MoneyitemID: ItemID
...
1..*
1..*
Register
...
enterItem(...)...
Sale
isComplete : Booleantime : DateTime
makeLineItem(...)
...1
1
1
catalog
currentSale
descriptions
{Map}
lineItems{ordered}
description
-
7/30/2019 Introduction to Object Oriented Design.pdf
39/87
Completion of item entry
-endSaleInteraction Diagram
:RegisterendSale(
s :Sale1: becomeComplete
by Expertby Controller
-
7/30/2019 Introduction to Object Oriented Design.pdf
40/87
sale.getTotalInteraction Diagram
:Saletot = getTotal 1 * [i = 1..n]: st = getSubtotal
:ProductDescription
1.1: pr = getPrice
lineItems[ i ]:SalesLineItem
by Expert by ExpertUML: note the selector
notation to select elementsfrom the lineItems collection
-
7/30/2019 Introduction to Object Oriented Design.pdf
41/87
Showing a method in a note symbol
:Saletot = getTotal 1 *[ i = 1..n]: st = getSubtotal
:ProductDescription
1.1: pr = getPrice
lineItems[ i ] :SalesLineItem
methodpublic void getTotal(){
int tot = 0;for each SalesLineItem, sli
tot = tot + sli.getSubtotal();return tot
}
-
7/30/2019 Introduction to Object Oriented Design.pdf
42/87
register.makePaymantInteraction
Diagram
1: makePayment(cashTendered)
1.1: create(cashTendered)
:Register :Sale
:Payment
makePayment(cashTendered)
by Controller by Creator and Low Coupling
-
7/30/2019 Introduction to Object Oriented Design.pdf
43/87
Logging a sale
Store
...
addSale(s : Sale)...
SalesLedger
...
addSale(s : Sale)...
Store is responsible forknowing and addingcompleted Sales.
Acceptable in earlydevelopment cycles if theStore has few
responsibilities.
SalesLedger is responsiblefor knowing and addingcompleted Sales.
Suitable when the designgrows and the Store
becomes uncohesive.
Sale
...
...
Sale
...
...
Logs-completed5 Logs-completed5* *
1 1
-
7/30/2019 Introduction to Object Oriented Design.pdf
44/87
Logging a completed sale
1: makePayment(cashTendered)
1.1: create(cashTendered)
:Register s :Sale
:Payment
makePayment(cashTendered)
:Store
2: addSale(s)
completedSales:List
2.1: add(s)
by Expert
note that the Sale instance is named's' so that it can be referenced as aparameter in messages 2 and 2.1
-
7/30/2019 Introduction to Object Oriented Design.pdf
45/87
Sale.getBalance Interaction Diagram
s :Sale pmt: Payment1: amt = getAmountbal = getBalance
2: t = getTotal
{ bal = pmt.amount - s.total }
A more complete DCD reflecting most
-
7/30/2019 Introduction to Object Oriented Design.pdf
46/87
A more complete DCD reflecting most
design decision
SalesLineItem
quantity : Integer
getSubtotal()
ProductCatalog
...
getProductDesc(...)
ProductDescription
description : Text
price : MoneyitemID: ItemID
...
Store
address : Addressname : Text
addCompleteSale(...)
Payment
amount : Money
...
1..*
1..*
Register
...
endSale()enterItem(...)
makeNewSale()makePayment(...)
Sale
isComplete : Booleantime : DateTime
becomeComplete()makeLineItem(...)makePayment(...)getTotal()
1
1
1
1
1
1
*
catalog
catalog
register
currentSale
descriptions{Map}
lineItems{ordered}
payment
completedSales{ordered}
description
-
7/30/2019 Introduction to Object Oriented Design.pdf
47/87
Design Class Diagram
Register
...
endSale()enterItem(...)makePayment(...)
Sale
timeisComplete : Boolean/total
makeLineItem(...)
Register
...
Sale
time
isComplete : Boolean/total
Captures
1
11
Domain Model
conceptualperspective
Design Model
DCD; softwareperspective
currentSale
-
7/30/2019 Introduction to Object Oriented Design.pdf
48/87
Determining Visibility Visibility is the ability of one object to see
or have reference to another. For an object A to send message to an
object B, B must be visible to A
-
7/30/2019 Introduction to Object Oriented Design.pdf
49/87
: RegisterenterItem
(itemID, quantity)
: ProductCatalog
desc = getProductDesc( itemID )
public void enterItem( itemID, qty ){...desc = catalog.getProductDesc(itemID)...
}
class Register{...private ProductCatalog catalog;...
}
Visibility from Register to ProductCatalog is required
-
7/30/2019 Introduction to Object Oriented Design.pdf
50/87
Four types of visibility from A to B
Attribute Visibility: B is an attribute of A Parameter visibility: B is a parameter of a
method of A.
Locally declared visibility: B is declared asa local object in a method of B
Global visibility: B is globally visible
Attribute visibility
-
7/30/2019 Introduction to Object Oriented Design.pdf
51/87
: RegisterenterItem(itemID, quantity)
: ProductCatalog
desc = getProductDesc( itemID )
public void enterItem(itemID, qty){...desc = catalog.getProductDesc(itemID)
...}
class Register{...private ProductCatalog catalog;
...}
y
Relatively permanent in nature ProductCatalog is an attribute of Register. Because register
needs to send getProductDescription message to catalog
ProductCatalog exists as long as Register exists
Parameter Visibility
-
7/30/2019 Introduction to Object Oriented Design.pdf
52/87
Parameter Visibility
Relatively temporary visibility Persists within the scope of the method
2: makeLineItem(desc, qty)nterItem(id, qty)
1: desc= getProductDesc(id)
2.1: create(desc, qty)
:Register :Sale
:ProductCatalog
sl : SalesLineItemmakeLineItem(ProductDescription desc, int qty){
...sl= new SalesLineItem (desc,qty);
...}
-
7/30/2019 Introduction to Object Oriented Design.pdf
53/87
Locally Declared Visibility
: RegisterenterItem
(itemID, quantity)
: ProductCatalog
desc = getProductDesc( itemID )
enterItem(id, qty){...
// local visibility via assignment of returning objectProductDescription desc = catalog.getProductDes(id);...}
-
7/30/2019 Introduction to Object Oriented Design.pdf
54/87
Global Visibility Least used
Least desirable Assign an instance to a global variable
Design Class Diagrams
-
7/30/2019 Introduction to Object Oriented Design.pdf
55/87
Design Class Diagrams
A design class diagram illustrates thespecifications for software classes andinterfaces in an application
Show dependencyrelationship
Do not show dependencyrelationship
Navigability arrowsindicate the direction ofvisibility
No navigability
Operations are presentOperations are absent
Software classesDomain level concepts
A design toolAn analysis toolDesign Class DiagramAnalysis Class Diagram
Steps in creating a Design Class
-
7/30/2019 Introduction to Object Oriented Design.pdf
56/87
Steps in creating a Design Class
Diagram Identify all the classes participating in the software
solution.
Draw them in a class diagram Duplicate the attributes from the associated concepts in
the analysis class diagram Add methods by analyzing interaction diagrams
Add type information to the attributes and the methods Add the association necessary to support attribute
visibility Add navigability arrow to indicate the direction of
attribute visibility Add dependency relationships to indicate non-attribute
visibility
Product
Records-sale-of
-
7/30/2019 Introduction to Object Oriented Design.pdf
57/87
Register
ItemStore
Sale
CashPayment
Sales
LineItem
CashierCustomer
Product
Catalog
ProductDescription
Stocks
*
Houses
1..*
Used-by
*
Contains1..*
Describes
*
Captured-on
Contained-in
1..*
0..1
Paid-by Is-for
Logs-
completed
*
3 Works-on
1
1
1
1 1..*
1
1
1
1
1
1
1
0..1 1
1
Ledger
Records-accounts-
for
1
1
NextGen POS partialDomain Model
Product
Records-sale-of
-
7/30/2019 Introduction to Object Oriented Design.pdf
58/87
Register
id
ItemStore
nameaddress
Sale
dateTime/ total
CashPayment
amountTendered
Sales
LineItem
quantity
Cashier
id
Customer
Product
Catalog
ProductDescription
itemIDdescriptionprice
Stocks
*
Houses
1..*
Used-by
*
Contains1..*
Describes
*
Captured-on
Contained-in
1..*
0..1
Paid-by Is-for
Logs-
completed
*
3Works-on
1
1
1
1 1..*
1
1
1
1
1
1
1
0..1 1
1
Ledger
Records-accounts-
for
1
1
NextGen POS partialDomain Model withsome attributes
A more complete DCD reflecting most
-
7/30/2019 Introduction to Object Oriented Design.pdf
59/87
A more complete DCD reflecting most
design decisions
SalesLineItem
quantity : Integer
getSubtotal()
ProductCatalog
...
getProductDesc(...)
ProductDescription
description : Text
price : MoneyitemID: ItemID
...
Store
address : Addressname : Text
addCompleteSale(...)
Payment
amount : Money
...
1..*
1..*
Register
...
endSale()enterItem(...)
makeNewSale()makePayment(...)
Sale
isComplete : Booleantime : DateTime
becomeComplete()makeLineItem(...)makePayment(...)
getTotal()
1
1
1
1
1
1
*
catalog
catalog
register
currentSale
descriptions{Map}
lineItems{ordered}
payment
completedSales{ordered}
description
Three tier architecture and packaging
-
7/30/2019 Introduction to Object Oriented Design.pdf
60/87
The three tier architecture
Presentation Layer
Windows, reports etc.
Application Layer
Tasks or rules that governs the process
Storage Layer
Persistent storage mechanism
Physical deployment
Client-server environment
Decomposition of Application Layer Domain Objects (Ex. Sale)
Services (Ex. Database interface)
-
7/30/2019 Introduction to Object Oriented Design.pdf
61/87
Packages Group of elements that provide a common
service (or a family of related services),with relatively high coupling andcollaboration.
At a higher level of abstraction theelements are highly cohesive (stronglycorrelated responsibility)
-
7/30/2019 Introduction to Object Oriented Design.pdf
62/87
Architecture Package Diagram
Presentation
Domain
Service
Database
Presentation
Application
Storage
-
7/30/2019 Introduction to Object Oriented Design.pdf
63/87
Layers and Partitions of Packages
CoreElements
Sales Product
DatabaseInterface
Communication
Security Reporting
Domain
Service
Layers
partitions
-
7/30/2019 Introduction to Object Oriented Design.pdf
64/87
Visibility between the packages Presentation packages have visibility into
many of the domain packages Presentation and domain packages have
visibility into only one or few classes in
each particular service package
No domain or service package have direct
visibility into presentation layer (IndirectCommunication)
No Direct Visibility to Windows
-
7/30/2019 Introduction to Object Oriented Design.pdf
65/87
y
The Model View Separation Pattern Problem: It is desirable to de-couple domain
(model) object from the windows (view) objects,to support increased reuse of domain object andminimize the impact of changes in the userinterface on the domain object. What to do?
Solution: Define domain (model) classes so thatthey do not have direct visibility to the windows(view) classes, and the application data andfunctionality remains with the domain classes,not with window classes.
Motivation for Model-View separation model
-
7/30/2019 Introduction to Object Oriented Design.pdf
66/87
p
To support cohesive model definitions that focus on thedomain processes, rather than computer interfaces.
To allow separate development of the model and theuser interface layers
To minimize the impact of requirements changes on theinterfaces upon the domain layer
To allow new views to be easily connected to an existingdomain layer, without affecting the domain layer.
To allow multiple simultaneous views on the same modelobject.
To allow the model layer independent of the userinterface layer, such as in in a message processing and
batch mode system. To allow easy porting of the model layer to another user
interface framework.
-
7/30/2019 Introduction to Object Oriented Design.pdf
67/87
How do the windows get the data? Polling or pull from above
It is the responsibility of a window object to ask for therelevant information from the other objects whenevernecessary.
Most common form
But fails when the information gets updated as aresult of the state change of the domain object (Ex.stock price, Network monitoring system)
Push-from-below model Publish Subscribe pattern
Indirect Communication in a System
-
7/30/2019 Introduction to Object Oriented Design.pdf
68/87
Publish-Subscribe Pattern Problem: A change in state (an event) occurs
within a Publisher of the event and the otherobjects are dependent on or are interested inthis event (Subscribed to the event). However,the publisher should not have the direct
knowledge of its subscribers. What to do?
Solution: Define an event notification system sothat the publisher can indirectly notify subscriber.
Ex. Mouse Listener, Keyboard listener
-
7/30/2019 Introduction to Object Oriented Design.pdf
69/87
Goal: When the total of the salechanges, refresh the display withthe new value
Sale
total...
setTotal( newTotal )...
{propertyListeners.add( lis );
}
{for each PropertyListener pl in propertyListeners
pl.onPropertyEvent( this, name, value );}
-
7/30/2019 Introduction to Object Oriented Design.pdf
70/87
interfacePropertyListener
onPropertyEvent( source, name, value )
SaleFrame1
onPropertyEvent( source, name, value )
initialize( Sale sale )...
javax.swing.JFrame
...setTitle()setVisible()...
{
if ( name.equals("sale.total") )saleTextField.setText( value.toString() );
}
Sale
addPropertyListener( PropertyListener lis )publishPropertyEvent( name, value )
setTotal( Money newTotal )...
*propertyListeners
{total = newTotal;publishPropertyEvent( "sale.total", total );
}
{sale.addPropertyListener( this )...
}
The observer SaleFrame1
-
7/30/2019 Introduction to Object Oriented Design.pdf
71/87
subscribes to publisher Sale
s : Salesf : SaleFrame1
initialize( s : Sale )
addPropertyListener( sf )
propertyListeners :
List
add( sf )
Sale publishes a property event to
-
7/30/2019 Introduction to Object Oriented Design.pdf
72/87
all its subscribers
s :Sale
setTotal( total )
onPropertyEvent( s, "sale.total", total )
publishPropertyEvent( "sale.total", total )
propertylisteners[ i ] :PropertyListener
loop
Subscriber SaleFrame1 receives
-
7/30/2019 Introduction to Object Oriented Design.pdf
73/87
notification of a published event
: SaleFrame1
onPropertyEvent( source, name, value )
saleTextField: JTextField
setText( value.toString() )
Since this is a polymorphic operation implemented bythis class, show a new interaction diagram that startswith this polymorphic version
UML notation: Note this little expression within theparameter. This is legal and consise.
Sale
addPropertyListener( PropertyListener lis )publishPropertyEvent( name, value )
publishes events toobservers/listeners/
b ib
-
7/30/2019 Introduction to Object Oriented Design.pdf
74/87
interfacePropertyListener
onPropertyEvent( source, name, value )
SaleFrame1
onPropertyEvent( source, name, value )
initialize( Sale sale )...
javax.swing.JFrame
...setTitle()setVisible()...
setTotal( Money newTotal )...
*propertyListeners
subscribers registers them when
they ask to subscribe
listens for events observes events subscribes to notification of events
-
7/30/2019 Introduction to Object Oriented Design.pdf
75/87
Few More Patterns More Grasp pattern
Polymorphism
Pure Fabrication
Indirection
Some GoF patterns Strategy
Faade
Command State
-
7/30/2019 Introduction to Object Oriented Design.pdf
76/87
Polymorphism Problem: How to handle alternatives based on type?
How to create pluggable software components?
Solution: When alternatives or behavior vary by type(class), assign responsibility for the behaviour-usingpolymorphic operations to the types for which thebehaviour varies.
Alternatives based on type Avoiding conditional variation within the program using if-then-
else or case structure
Pluggable s/w component
Client server environment Replacing one server component with other without affecting the
client.
interfaceITaxCalculatorAdapter
getTaxes( Sale ) : List
How to supportthird party tax
-
7/30/2019 Introduction to Object Oriented Design.pdf
77/87
TaxMasterAdapter
getTaxes( Sale ) : List
GoodAsGoldTaxProAdapter
getTaxes( Sale ) : List
By Polymorphism, multiple tax calculator adapters havetheir own similar, but varying behavior for adapting todifferent external tax calculators.
Adapter
...
...
p y
calculators?
These are not the third party
software, but an interface that connects to the third party software
-
7/30/2019 Introduction to Object Oriented Design.pdf
78/87
Pure Fabrication Problem: Who should take the responsibility when you donot want to violate High Cohesion and Low coupling orother goals, but the solution provided by the expert is not
appropriate ?
Solution: Assign a high cohesive set of responsibilities toan artificial class that does not represent any thing in the
problem domain.
Ex: Saving sales in a database Sale class has the necessary information to store itself.
But
Sale class has to be coupled with relational database interface (not adomain level concept)
Type of relational database may change in the future
-
7/30/2019 Introduction to Object Oriented Design.pdf
79/87
Persistent Storage
Insert(Object)Update(Object)
By Pure Fabrication
Indirection
-
7/30/2019 Introduction to Object Oriented Design.pdf
80/87
Problem: How to avoid direct coupling? How todecouple objects so that Low Coupling issupported and the reuse potential remains high?
Solution: Assign the responsibility to mediatebetween the other components or services sothat they are not directly coupled.
The intermediary creates an indirection betweenthe other components or services.
: Sale :TaxMasterAdapter
-
7/30/2019 Introduction to Object Oriented Design.pdf
81/87
taxes = getTaxes( s )
t = getTotal
the adapter acts as a level of
indirection to external systems
TCP socketcommunication
xxx...
actor
:TaxMasterSystem. . .
Strategy
-
7/30/2019 Introduction to Object Oriented Design.pdf
82/87
gy
Problem: How to design for varying but
related, algorithms or policies? How todesign for the ability to change thesealgorithms or policies?
Solution: Define each algorithm/policy/strategy in a separate class, with acommon interface.
interfaceISalePricingStrategy
getTotal( Sale ) : Money
-
7/30/2019 Introduction to Object Oriented Design.pdf
83/87
PercentDiscountPricingStrategy
percentage : float
getTotal( s:Sale ) :Money
AbsoluteDiscountOverThresholdPricingStrategy
discount : Moneythreshold : Money
getTotal( s:Sale ) :Money
{return s.getPreDiscountTotal() * percentage
}
???PricingStrategy
...
...
{
pdt := s.getPreDiscountTotal()
if ( pdt < threshold )return pdt
elsereturn pdt - discount
}
Faade (A front end object)
-
7/30/2019 Introduction to Object Oriented Design.pdf
84/87
( j )
A common, unified interface to a disparate set ofimplementation within a subsystem are required.There may be undesirable coupling to manythings in the subsystem, or the implementationof the subsystem may change. What to do?
Define a single point of contact to thesubsystem- a faade object that wraps thesubsystem. This faade object represents a
single unified interface and is responsible forcollaborating with the subsystem components.
Domain
package name may beshown in the tab
-
7/30/2019 Introduction to Object Oriented Design.pdf
85/87
+ Sale + Register ...
POSRuleEngine
interface- IRule
...
- Rule1
...
- Rule2
...
...
visibility of the package element (tooutside the package) can be shownby preceding the element name with avisibility symbol
+ POSRuleEngineFacade
instance : RuleEngineFacade
getInstance() : RuleEngineFacade
isInvalid( SalesLineItem, Sale )isInvalid( Payment, Sale )...
*
State
-
7/30/2019 Introduction to Object Oriented Design.pdf
86/87
Problem: An objects behavior is dependent onstate. Conditional logic is undesirable because
of complexity, scalability or duplication. What todo? Solution:
Create a class for each state that influences the
behavior of the sate dependent objects (the contextobject)
Based on the polymorphism, assign methods to eachstate class to handle the behaviour of the context
object When the state dependent message is received bythe context object forward it to the state object.
Command
-
7/30/2019 Introduction to Object Oriented Design.pdf
87/87
Problem: A variety of requests or commands canbe received by an object or system. How toreduce the receivers responsibility in handlingthe commands, increase the ease with whichnew commands may be added, and provide a
foundation for logging, queuing and undoingcommands?
Solution: For each command, define a class that
represents it and give it responsibility forexecuting itself.