Observer & Decorator: Patterns
Observer & Decorator: Patterns
&
DECORATOR
PATTERNS
Observer Pattern
■ Define a one-to-many dependency between objects so that when one object changes state, all its
dependents are notified and updated automatically.
■ Define an object that is the "keeper" of the data model and/or business logic (the Subject).
■ Observers register themselves with the Subject as they are created. Whenever the Subject changes, it
broadcasts to all registered Observers that it has changed, and each Observer queries the Subject for
that subset of the Subject's state that it is responsible for monitoring.
Observer Pattern: Structure
Observer Pattern: Example
■ Each bidder possesses a numbered paddle that
is used to indicate a bid.
■ It is a "pull" interaction model. Instead of the Subject "pushing" what has changed to all
Observers, each Observer is responsible for "pulling" its particular "window of interest" from the
Subject.
■ At the discretion of the designer, include: implementing event compression (only sending a single
change broadcast after a series of consecutive changes has occurred), having a single Observer
monitoring multiple Subjects, and ensuring that a Subject notify its Observers when it is about to
go away.
Observer Pattern: Question (Take 10 mins)
A news agency gathers news and publishes them to different subscribers. We need to
create a framework for the agency to be able to inform immediately, when an event
occurs, its subscribers about the event. The subscribers can receive the news in
different ways: Emails, SMS, ... The solution needs to be extensive enough to support
new types of subscribers (maybe new communication technologies will appear).
Observer Pattern: Answer
Decorator Pattern
■ The ornaments that are added to Christmas trees are examples of Decorators.
Intent
■ This pattern creates a decorator class which wraps the original class and
provides additional functionality keeping class methods signature intact.
Now based on these definitions, how would you design the following-
1) A luxury car
2) A sports car
3) A luxury car that is also a sports car
Decorator : Answer
public class CarDecorator implements Car {
protected Car car;
public CarDecorator(Car c){
this.car=c;
}
@Override
public void assemble() {
this.car.assemble();
}
}
Decorator : Answer
public class SportsCar extends CarDecorator{ public class LuxuryCar extends CarDecorator{
public SportsCar(Car c) { public LuxuryCar(Car c) {
super(c); super(c);
} }
@Override @Override
public void assemble(){ public void assemble(){
car.assemble(); car.assemble();
System.out.print(" Adding features System.out.print(" Adding
of Sports Car."); features of Luxury Car.");
} }
} }
Decorator : Answer
public class DecoratorPatternClass{