Software Design and Construction 1
SOFT2201 / COMP9201
Adapter and Observer Dr. Xi Wu
School of Computer Science
The University of Sydney
Page 1
Copyright warning
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING
This material has been reproduced and communicated to you by or on behalf of the University of Sydney
pursuant to Part VB of the Copyright Act 1968 (the Act).
The material in this communication may be subject to copyright under the Act. Any further copying or communication of this material by you may be the subject of copyright protection under
the Act.
Do not remove this notice.
The University of Sydney Page 2
Agenda
– Structural Design Pattern – Adapter
– Behavioural Design Pattern – Observer
The University of Sydney
Page 3
Structural Design Patterns
The University of Sydney Page 4
Structural Design Patterns
– How classes and objects are composed to form larger structures
– Structural class patterns use inheritance to compose interfaces
or implementations
– Structural object patterns describe ways to compose objects to realise new functionality
– Theflexibilityofobjectcompositioncomesfromtheabilitytochangethe composition at run-time
The University of Sydney Page 5
Structural Patterns (GoF)
Pattern Name
Description
Adapter
Allow classes of incompatible interfaces to work together. Convert the interface of a class into another interface that clients expect.
Façade
Provides a unified interface to a set of interfaces in a subsystem. Defines a higher-level interface that makes the subsystem easier to use.
Decorator
Attach additional responsibilities to an object dynamically (flexible alternative to subclassing for extending functionality)
Composite
Compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly
Flyweight
Use sharing to support large numbers of fine-grained objects efficiently.
Bridge
Decouple an abstraction from its implementation so that the two can vary independently
Proxy
Provide a placeholder for another object to control access to it
The University of Sydney Page 6
Adapter Pattern
Class, Object Structural
The University of Sydney Page 7
Adapter
– Intent
– Convert the interface of a class into another interface that clients
expect.
– Lets classes work together that couldn’t otherwise because of incompatible interfaces.
– Known as
– Wrapper
– Motivation
– Sometimes existing code that has the functionality we want doesn’t have
the right interface we want to use
The University of Sydney Page 8
Adapter
– Applicability
– Touseanexistingclasswithaninterfacedoesnotmatchtheoneyouneed
– Youwanttocreateareusableclassthatcooperateswithunrelatedor unforeseen classes, i.e., classes that don’t necessarily have compatible interfaces
– (Objectadapteronly)Adaptanexistinginterface,whichhasseveralexisting implementations.
– Benefits
– Codereuse
The University of Sydney Page 9
Class Adapter – Structure
• Request multiple inheritance to adapt the Adaptee to Target, supported by C++
The University of Sydney Page 10
Object Adapter – Structure
The University of Sydney Page 11
Adapter – Participants
– Target
– Definesthedomain-specificinterfacethatClientuses
– Client
– CollaborateswithobjectsconformingtotheTargetinterface.
– Adaptee
– Definesanexistinginterfacethatneedsadapting.
– Adapter
– AdaptstheinterfaceofAdapteetotheTargetinterface
– Collaborations
– ClientscalloperationsonanAdapterinstance.Inturn,theAdaptercallsAdaptee
operations that carry out the request
The University of Sydney Page 12
Class Adapter – Consequences
– When we want to adapt a class and all its subclasses, a class adapter won’t work
– ItadaptsAdapteetoTargetbycommittingtoaconcreteAdapteeclass
– Lets Adapter override some of Adaptee’s behavior, since Adapter is a
subclass of Adaptee
– Introduces only one object, and no additional pointer indirection is needed to get to the Adaptee (for programming language such as C++)
The University of Sydney Page 13
Object Adapter – Consequences
– Lets a single Adapter work with many Adaptees – i.e., the Adaptee itself and all of its subclasses (if any).
– Makes it harder to override Adaptee behavior. It will require sub-classing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself
The University of Sydney Page 14
Adapter Example — Problem
Shape
+setLocation() +getLocation() +display() +fill() +setColor() +undisplay()
XXCircle
+setLocation() +getLocation() +displayit() +fillit() +setItsColor() +undisplayIt()
Line
+display() +fill() +undisplay()
Square
+display() +fill() +undisplay()
The University of Sydney Page 15
Adapter Example — Solution
class Circle extends Shape{ …
private XXCircle myXXCircle; ..
public Circle(){
myXXCircle = new XXCircle(); }
void public display(){ myXXcircle.displayIt();
}
… }
Shape
+setLocation() +getLocation() +display() +fill() +setColor() +undisplay()
XXCircle
+setLocation() +getLocation() +displayit() +fillit() +setItsColor() +undisplayIt()
Line
+display() +fill() +undisplay()
Square
Circle
+getlocation() +setLocation() +display() +fill() +setColor() +undisplay()
+display() +fill() +undisplay()
The University of Sydney
Page 16
11
Adapter pattern: general structure
– Target (Shape)
– defines the domain-specific interface that
Client uses.
– Adapter (Circle)
– adapts the interface Adaptee to the
Target interface. – Adaptee (XXCircle)
– defines an existing interface that needs adapting.
– Client (ShapeApp)
– collaborates with objects conforming to the Target interface.
The University of Sydney
Page 17
Different Implementations of Adapter
class Circle implements Shape extends XXCircle{ …
..
public Circle( double radius){
super( radius); }
void public display(){ super.displayIt();
}
… }
«interface»
Shape
+display() +fill() +undisplay()
XXCircle
+setLocation() +getLocation() +displayit() +fillit() +setItsColor() +undisplayIt()
Line
+display() +fill() +undisplay()
Square
Circle
+getlocation() +setLocation() +display() +fill() +setColor() +undisplay()
+display() +fill() +undisplay()
The University of Sydney Page 18
Object Adapter and Class Adapter
– Object Adapter
– Relies on object composition to achieve adapter
– Class Adapter
– Relies on class inheritance to achieve adapter
The University of Sydney
Page 33
Two Reuse Mechanisms
– Inheritance and Delegation
– Inheritance:reusebysubclassing;
• “is-a” relationship (white-box reuse)
– Delegation:reusebycomposition;
• “has-a” relationship (black-box reuse)
• A class is said to delegate another class if it implements an operation by resending a message to another class
– Rule of thumb – design principles #1
– Favourobjectcompositionoverclassinheritance
The University of Sydney Page 34
Observer Pattern
Object Behavioural
The University of Sydney Page 38
Observer
– Intent
– Defineaone-to-manydependencybetweenobjectssothatwhenoneobject
changes state, all its dependents are notified and updated automatically
– Known as
– Dependents,Publish-Subscribe
– Motivation:
– Acollectionofcooperatingclasses(consistencybetweenrelatedobjects)
– Consistencywhilemaintainingloosely-coupled,andhighlyreusableclasses
The University of Sydney
Page 39
Observer – Applicability
– An abstraction has two aspects, one dependent on the other
– A change to one object requires changing others, and it’s not clear how many objects
need to be changed
– An object should be able to notify other objects without making assumptions about who these objects are
The University of Sydney Page 40
Observer – Publish-Subscribe
– Problem
– You need to notify a varying list of objects that an event has occurred
– Solution
– Subscriber/listener interface
– Publisher: dynamically register interested subscribers and notify them when an event occurs
The University of Sydney Page 41
Observer – Example (Data Representation)
The University of Sydney Page 42
Observer – Structure
The University of Sydney Page 43
Observer – Participants
Participant
Goals
Subject
Knows its observers. Any number of observer objects may observe a subject. Provides an interface for attaching and detaching observer objects
Observer
Defines an updating interface for objects that should be notified of changes in a subject
ConcreteSubject
Stores state of interest to ConcreteObserver objects Sends notifications to its observers when its state changes
ConcreteObserver
Maintains a reference to a ConcreteSubject object
Stores state that should stay consistent with the subject’s.
Implements the observer’s updating interface to keep its state consistent
The University of Sydney Page 44
Observer – Consequences
– Abstract coupling between Subject and Observer
– Subject only knows its Observers through the abstract Observer class (it doesn’t know the
concrete class of any observer)
– Support for broadcast communication
– Notifications are broadcast automatically to all interested objects that subscribe to the Subject
– Add/remove Observers anytime
– Unexpected updates
– Observers have no knowledge of each other’s presence, so they can be blind to the cost of changing the subject
– An innocent operation on the subject may cause a cascade of updates to Observers and their dependents
The University of Sydney Page 46
Observer – NextGen PoS System
– PoS system requirement (iteration 2):
Goal: When the total of the sale changes, refresh the display with the new value
Sale
setTotal( newTotal ) …
total …
One solution:
When the Sale object changes its total, the Sale object sends a message to a window (GUI), asking it to refresh its display
Discuss: good/bad solution? Why/why not?
The University of Sydney
Page 47
–
Observer – NextGen PoS System
Model-view separation principle (low-coupling of model and UI layers)
– “model” (e.g., Sale object) should not know/update “view” presentation objects (e.g., window)
– Allows replacing (or changing) the UI without influencing the model (Sale object)
Goal: When the total of the sale changes, refresh the display with the new value
Sale
setTotal( newTotal ) …
total …
The University of Sydney
Page 49
Observer – NextGen POS Solution
{
for each PropertyListener pl in propertyListeners
pl.onPropertyEvent( this, name, value ); }
{
propertyListeners.add( lis );
}
Sale
addPropertyListener( PropertyListener lis ) publishPropertyEvent( name, value )
setTotal( Money newTotal ) …
{
total = newTotal;
publishPropertyEvent( “sale.total”, total );
}
javax.swing.JFrame
… setTitle() setVisible() …
propertyListeners
* «interface»
PropertyListener onPropertyEvent( source, name, value )
SaleFrame1 onPropertyEvent( source, name, value )
initialize( Sale sale ) …
{
if ( name.equals(“sale.total”) )
saleTextField.setText( value.toString() ); }
{
sale.addPropertyListener( this ) …
}
The University of Sydney
Page 50
Observer – NexTGen POS Solution
– An interface is defined – PropertyListener with the operation onPropertyEvent
– Define an UI object to implement the interface — SalesFrame1
– When the SalesFrame1 window is initialised, pass it the Sale instance from which it
is displaying the total
– The SaleFrame1 window registers or subscribes to the Sale instance for
notification of “property events”, via the addPropertyListener message.
– The Sale instance, once its total changes, iterates across all subscribing
PropertyListeners, notifying each The University of Sydney
Page 51
Observer – Subscribe To Publisher
sf : SaleFrame1
s : Sale
initialize( s : Sale )
The University of Sydney
Page 52
addPropertyListener( sf )
propertyListeners : List
add( sf )
Sale publishes a property events to all subscribers
s :Sale
setTotal( total )
publishPropertyEvent ( “sale.total”, total )
loop
onPropertyEvent( s, “sale.total”, total )
propertylisteners[ i ] : PropertyListener
The University of Sydney
Page 53
Subscriber Receives A Notification
Since this is a polymorphic operation implemented by this class, show a new interaction diagram that starts with this polymorphic version
The University of Sydney
Page 54
onPropertyEvent( source, name, value )
: SaleFrame1
saleT extField : JTextField
setText( value.toString() )
UML notation: Note this little expression within the parameter. This is legal and consise.
Task for Week 9
• Submit weekly exercise on canvas before 23.59pm Sunday
• Well organize time for assignment 3 once it is released
• Attend Helpdesk session if you have any questions/difficulties on implementation perspective
• Prepare questions and ask during tutor Q&A session this week
• Self learning on Next Gen POS system once it is released today
The University of Sydney Page 61
What are we going to learn on week 10?
• Creational Design Pattern – Prototype
• Behavioral Design pattern – Memento
The University of Sydney
Page 62
References
– Craig Larman. 2004. Applying UML and Patterns: An Introduction to Object- Oriented Analysis and Design and Iterative Development (3rd Edition). Prentice Hall PTR, Upper Saddle River, NJ, USA.
– Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
1995. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Longman Publishing Co., Inc., Boston, MA, USA.
The University of Sydney
Page 63