Lecture 9 - Design - Patterns - 4patterns
Lecture 9 - Design - Patterns - 4patterns
public MyClass {
public static MyClass getInstance ( ) { }
}
public MyClass {
private MyClass ( ) { }
public static MyClass getInstance ( ) { }
}
The Classic Singleton Pattern
public class Singleton {
Constructor is private static Singleton uniqueInstance;
declared private; // other useful instance variables
only singleton can
We have a static
instantiate this
private Singleton ( ) { } variable to hold
class!
our one instance
public static Singleton getInstance ( ) { of the class
if (uniqueInstance == null) { Singleton.
uniqueInstance = new Singleton ( );
}
The getInstance ( ) method
gives us a way to instantiate return uniqueInstance;
the class and also return an }
instance of it.
if (uniqueInstance == null) {
uniqueInstance = new Singleton ( );
}
return uniqueInstance;
Screen
up () TheaterLights
down ( ) on ( )
off ( ) Projector
CdPlayer dvdPlayer
dim ( )
amplifier on ()
on () off ( )
off ( ) tvMode ( )
PopcornPopper eject ( ) wideScreenMode ( )
on ( ) pause ( )
off ( ) play ( )
pop ( ) stop ( )
Watching a Movie the Hard Way!
1. Turn on the popcorn popper
2. Start the popper popping
3. Dim the lights
4. Put the screen down
5. Turn the projector on But there’s more!
6. Set the projector input to DVD When the movie is done, how
7. Put the projector on wide-screen mode do you turn everything off? Do
you reverse all the steps?
8. Turn the sound amplifier on Wouldn’t it be just as complex
9. Set the amplifier to DVD input to listen to a CD or radio?
10. Set the amplifier to surround sound If you decide to upgrade your
system, you’re probably going
11. Set the amplifier volume to medium (5) to have to learn a slightly
12. Turn the DVD player on different procedure!
13. Start the DVD player playing.
Façade to the Rescue!!
14. Whew!
Lights, Camera, Façade! HomeTheaterFacade
(1) Create a Façade for the (2) The Façade treats the home
HomeTheater which exposes a few watchMovie ()
endMovie () theater components as its subsystem,
simple methods such as watchMovie ( ) and calls on the subsystem to
listenToCD ( )
endCD () implement its watchMovie ( ) method.
listenToRadio ()
endRadio ( )
(4) The Façade still leaves
the subsystem accessible to
(3) The Client now Amplifier be used directly.
calls methods on the tuner
dvdPlayer
façade and not on DvdPlayer
cdPlayer
the subsystem. Tuner
on () amplifier
amplifier on ()
off ( )
on () off ( )
setCD( )
off ( ) eject ( )
setDVD ( )
setAM ( ) pause ( )
setStereoSound ( )
setFM ( ) play ( )
setSurroundSound ( )
setFrequency ( ) setSurroundAudio ( )
setTuner ( )
setVolume ( ) setTwoChannelAudio ( )
stop ( )
Screen
up () TheaterLights
down ( ) on ( )
The subsystem off ( ) Projector
CdPlayer dvdPlayer
the façade is dim ( )
amplifier on ()
simplifying. on () off ( )
off ( ) tvMode ( )
PopcornPopper eject ( ) wideScreenMode ( )
on ( ) pause ( )
off ( ) play ( )
pop ( ) stop ( )
The Façade Defined
The Façade Pattern provides a unified interface to a set of interfaces in a subsytem.
Façade defines a higher-level interface that makes the subsystem easier to use.
Unified interface
Happy client that is easier to use.
whose job just Client Facade
became easier
because of the
façade.
Your Existing Vendor Their interface doesn’t match the one you’ve
System Class written your code against. Not going to work!
The adapter
– What to do? Write a class that adapts the new vendor interface into the one
implements And talks to the vendor interface to service
the
interface
you’re expecting. your requests
your classes
Your Existing Vendor Your Existing Adapter Vendor
expect
System
Adapter
Class == System Class
No code changes
No code changes New code
If it walks like a duck…..
• If it walks like a duck and quacks like a duck, then it
might be a duck turkey wrapped with a duck adapter….
public interface Duck { Meet the fowl!
public void quack ();
public void fly (); public interface Turkey {
} public void gobble ();
public class MallardDuck implements Duck { public void fly ( );
public void quack () { }
System.out.println(“Quack”);
} public class WildTurkey implements Turkey {
public void fly ( ) { public void gobble ( ) {
System.out.println(“Gobble Gobble”);
System.out.println (“I am flying”);
}
}
public void fly ( ){
} System.out.println(“I’m flying a short distance”);
}
}
Client <<Interface>>
Target The Adapter implements the target
request ( ) interface
The client sees only the
Target interface.
Full
Full of
of good
good OO
OO design
design principles:
principles:
--Use
--Use ofof object
object composition
composition
--Pattern
--Pattern binds
binds the
the client
client to
to an
an Adapter Adaptee
interface and not an implementation
interface and not an implementation request ( ) specificRequest ()
Temp: 72
Humidity: 60
Temperature Sensor Pressure:
Device
Weather Station
Display Device
Pressure Sensor
Device
The Job: Create an app that uses the WeatherData object to update
three displays for current conditions, weather stats, and a forecast.
Time for the Observer!
• The Newspaper or Magazine subscription model:
– A newspaper publisher goes into business and begins
publishing newspapers
– You subscribe to a particular newspaper, and every time there
is a new edition, its gets delivered to you. As long as you
remain a subscriber, you get new newspapers.
– You unsubscribe when you don’t want the newspapers
anymore -- and they stop being delivered
– While the publisher remains in business people, hotels,
airlines etc constantly subscribe and unsubscribe to the
newspaper.
Publishers + Subscribers = Observer Pattern
The observers have subscribed to the
Subject to receive updates when the
• Publisher == Subject subject’s data changes.
• Subscribers == Observers
2 2
2 2
int 2
Dependent objects
(observers are
dependent on the
subject to update
Observer Objects them when data
Automatic update/notification changes.)
Observer Class Diagram
Here’s the Subject interface. Objects use All potential observers need to
this interface to register as observers and implement the Observer
also to remove themselves from being Each subject can have
many observers interface. This interface has just
observers. one method, update ( ), that gets
called when the Subject’s state
changes.
A concrete subject always implements the Subject interface. In addition Concrete observers can be any class that
to the register (attach) and remove (detach) methods, the concrete implements the Observer interface. Each
subject implements a notify() method to notify observers whenever state observer registers with a concrete subject to
changes. receive updates.
Designing the Weather Station Create an interface for all display
All weather components implement the Observer elements to implement. The display
Subject interface interface. This gives the subject a common elements just need to implement a
interface to talk to when it comes time to update. display ( ) method.
CurrentConditions ForecastDisplay
update ( ) update ( )
WeatherData display ( ) { // display display ( ) { // display
current measurements } the forecast }
registerObservers ( )
removeObservers ( )
notifyObservers ( )
StatisticsDisplay
getTemperature ( )
getHumidity ( ) update ( )
getPressure ( ) display ( ) { // display
measurementsChanged ( ) avg, min, and max
measurements }
WeatherData now
implements the Subject
interface.
Implementing the Weather Station
public interface Subject {
public void registerObserver (Observer o); Both of these methods take an Observer
public void removeObserver (Observer o); as an argument, that is the Observer to
be registered or removed.
public void notifyObservers ( );
}
This method is called to notify all
observers when the Subject’s state has
public interface Observer { changed.
public void update (float temp, float humidity, float pressure); The Observer interface is
} implemented by all observers,
so they all have to implement
the update ( ) method.
public interface DisplayElement {
public void display ( );
} These are the state values
the Observers get from the
Subject when a weather
measurement changes.