SOFT2201-java代写
时间:2023-09-15
The University of Sydney Page 1
Software Design and
Construction 1
SOFT2201 / COMP9201
Adapter and Observer
School of Computer Science
In your opinion, why do we need to
apply design patterns?
The University of Sydney Page 2
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 3
Agenda
– Structural Design Pattern
– Adapter
– Behavioural Design Pattern
– Observer
The University of Sydney Page 4
Structural Design Patterns
The University of Sydney Page 5
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
– The flexibility of object composition comes from the ability to change the
composition at run-time
The University of Sydney Page 6
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 7
Adapter Pattern
Class, Object Structural
The University of Sydney Page 8
Motivated Scenario
– Suppose you travel to European countries with your laptop you
have bought in Australia.
Power Charger for Computer European Power Strip
Adapter
The University of Sydney Page 9
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.
– Sometimes existing code that has the functionality we want doesn’t have
the right interface we want to use
– Known as
– Wrapper
The University of Sydney Page 10
Class Adapter – Structure
• Request multiple inheritance to adapt the Adaptee to Target, supported by C++
The University of Sydney Page 11
Object Adapter – Structure
Defines the domain-specific interface that Client uses
Defines an existing interface that
needs adapting
Adapts the interface of Adaptee to the Target interface
The University of Sydney Page 12
Adapter – Participants
– Target
– Defines the domain-specific interface that Client uses
– Client
– Collaborates with objects conforming to the Target interface.
– Adaptee
– Defines an existing interface that needs adapting.
– Adapter
– Adapts the interface of Adaptee to the Target interface
The University of Sydney Page 13
Adapter
– Applicability
– To use an existing class with an interface does not match the one you need
– You want to create a reusable class that cooperates with unrelated or
unforeseen classes, i.e., classes that don't necessarily have compatible interfaces
– (Object adapter only) Adapt an existing interface, which has several existing
implementations.
– Benefits
– Code reuse
– Collaborations
– Clients call operations on an Adapter instance. In turn, the Adapter calls
Adaptee operations that carry out the request
The University of Sydney Page 14
Class Adapter – Consequences
– When we want to adapt a class and all its subclasses, a class adapter won’t
work
– It adapts Adaptee to Target by committing to a concrete Adaptee class
– Lets Adapter override some of Adaptee’s behavior, since Adapter is a
subclass of Adaptee
The University of Sydney Page 15
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 16
Adapter Example -- Problem
+setLocation()
+getLocation()
+display()
+fill()
+setColor()
+undisplay()
Shape
+display()
+fill()
+undisplay()
Line
+display()
+fill()
+undisplay()
Square
+setLocation()
+getLocation()
+displayit()
+fillit()
+setItsColor()
+undisplayIt()
XXCircle
The University of Sydney Page 17
Adapter Example: Identify Participants
– 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 18
Adapter Example -- Solution
+setLocation()
+getLocation()
+display()
+fill()
+setColor()
+undisplay()
Shape
+display()
+fill()
+undisplay()
Line
+display()
+fill()
+undisplay()
Square
+setLocation()
+getLocation()
+displayit()
+fillit()
+setItsColor()
+undisplayIt()
XXCircle
+getlocation()
+setLocation()
+display()
+fill()
+setColor()
+undisplay()
Circle
1 1
class Circle extends Shape{
…
private XXCircle myXXCircle;
..
public Circle(){
myXXCircle = new XXCircle();
}
void public display(){
myXXcircle.displayIt();
}
…
}
What should a client do?
Shape shape = new Circle();
shape.display();
The University of Sydney Page 19
Different Implementations of Adapter
+display()
+fill()
+undisplay()
Line
+display()
+fill()
+undisplay()
Square
+setLocation()
+getLocation()
+displayit()
+fillit()
+setItsColor()
+undisplayIt()
XXCircle
+getlocation()
+setLocation()
+display()
+fill()
+setColor()
+undisplay()
Circle
class Circle extends XXCircle implements Shape {
…
..
public Circle( double radius){
super( radius);
}
void public display(){
super.displayIt();
}
…
}
+display()
+fill()
+undisplay()
«interface»
Shape
The University of Sydney Page 20
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 21
Two Reuse Mechanisms
– Inheritance and Delegation
– Inheritance: reuse by subclassing;
• “is-a” relationship (white-box reuse)
– Delegation: reuse by composition;
• “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
– Favour object composition over class inheritance
The University of Sydney Page 22
Observer Pattern
Object Behavioural
The University of Sydney Page 23
Motivated Scenario
– Anytime the SOFT2201/COMP9201 teaching team sent an
announcement on Ed, all students enrolled in these two units
could be notified by receiving an email.
A1 marks has been released
The University of Sydney Page 24
Observer
– Intent
– Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically
– A collection of cooperating classes (consistency between related objects)
– Known as
– Dependents, Publish-Subscribe
The University of Sydney Page 25
Observer – Structure
The University of Sydney Page 26
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 27
Revisit the Motivated Example
Subject Perspective
The University of Sydney Page 28
Revisit the Motivated Example
Observer Perspective
Client Perspective
The University of Sydney Page 29
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 30
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 31
Observer – Example (Data Representation)
The University of Sydney Page 32
Observer – Collaborations
The University of Sydney Page 33
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 34
Observer In GUI Class Library
– Observer pattern is the basic structure of event handling system in Java’s
GUI library
– Each GUI widget is a publisher of GUI related events
– ActionEvent, MouseClickedEvent, ListSelectionEvent,…
– Observer can be any other objects (GUI or non-GUI objects)
The University of Sydney Page 35
Observer in Java GUI
– Example
– A simple GUI with a JTextField and a JList component
– Each time the List is selected, the selected text is displayed in the
JTextField.
– JList supports ListSelectionListener
– A subclass of JTextField should implements
ListSelectionListener
The University of Sydney Page 36
Observer in Java GUI
The University of Sydney Page 38
Publisher-Many-Subscribers
– One publisher instance could have zero to many registered subscribers
– E.g., one instance of an AlarmClock could have three registered alarm windows, four
Beepers, and on ReliabilityWatchDog
– When an alarm even happens, all eight of these AlarmListeners are notified via an
onAlarmEvent
– Observer Implementation (Java)
– Events are communicated via a regular message, such as on onPropertyEvent
– Event is more formally defined as a class, and filled with appropriate event data
– The event is then passed as a parameter in the event message
The University of Sydney Page 39
Publisher-Many-
Subscribers
«interface»
AlarmListener
onAlarmEvent( source, time )
Beeper
onAlarmEvent( source, time )
...
{
display notification dialog
box
}
AlarmClock
addAlarmnListener( AlarmListener lis )
publishAlarmEvent( time )
setTime( newTime )
...
*alarmListeners
{
time = newTime;
if ( time == alarmTime )
publishAlarmEvent( time );
}
{
alarmListeners.add( lis );
}
{
for each AlarmListener al in alarmListeners
al.onAlarmEvent( this, time );
}
AlarmWindow
onAlarmEvent( source, time )
...
javax.swing.JFrame
...
setTitle()
setVisible()
...
ReliabilityWatchDog
onAlarmEvent( source, time )
...
{
beep
}
{
check that all required processes
are executing normally
}
The University of Sydney Page 40
Task for Week 7
• Submit weekly exercise on canvas before 23.59pm Saturday
• Well organize your time for assignment 2
• Prepare questions and ask during tutorials
• Self learning on Next Gen POS system
The University of Sydney Page 41
What are we going to learn in week 8?
• Code Review
The University of Sydney Page 42
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.