OO Design Patterns: Session 2 Observer, Strategy, Decorator
OO Design Patterns: Session 2 Observer, Strategy, Decorator
Session 2
Observer, Strategy, Decorator
Observer Pattern
Category : Behavioral
The Observer Pattern allows one or
more objects (Observer) to monitor
another object (Subject).
A subset of the Pub-Sub Pattern
When the state of one object changes,
dependants are notified
Observer Pattern
OO Principals
Promotes loose couplings
The Subject does not need to be aware of
Observers except at runtime
Favors composition over inheritance
Program to an interface
Observer Pattern
Basic Structure
Observalable Subject
1 or more Observers
Observer Pattern – Observer
interface
void update(Observable o, Object arg)
Observer Pattern – SUN Impl
Example
Observer Pattern
Q&A
Decorator Pattern
Category : Structural
The Decorator Pattern allows
responsibility and functionality to be
added dynamically at run-time
Provides a flexible alternative to sub-
classing to extend functionality
Decorator Pattern
OO Principals
Encapsulate what varies
Favor composition over inheritance
Program to interfaces
Open/closed principle
Objects should be open for extension, but
closed for modification
Basic Structure
Abstract Component Class
Concrete Components
Abstract Decorator
Concrete Decorator
Decorator Pattern
Basic Structure
Abstract Component Class
A common ancestor that all involved objects
extend
Decorator Pattern
Basic Structure
Concrete Components
The object to add dynamic behaviors to
Decorator Pattern
Basic Structure
Abstract Decorator
Enforces the contract of the Abstract Component
Class
Allows for more decorator specific behaviors to be
defined
Decorator Pattern
Basic Structure
Concrete Decorator
Implements the specific behavior
Decorator Pattern
Cons
Can Cause “Class Explosion”
Each Decorator is a class
Code can be hard to find/debug
Strategy Pattern
Category : Behavioral
Allows algorithms vary independently
from clients that use them
Strategy Pattern
OO Principals
Encapsulate what varies
Favor composition over inheritance
Program to interfaces
Basic structure
Context
Strategy Interface
Concrete Strategies
Strategy Pattern
Context
Is Configured with a
Concrete Strategy
Initiates the work of
the Strategy via the
Strategy Interface
May provide and
interface for the
Strategy to access
it Data
Strategy Pattern
Strategy Interface
Defines a way for
the Context to
interact with each
algorithm
Strategy Pattern
Concrete Strategy
Encapsulates the
algorithm
Performs the actual
work
Strategy Pattern
Q&A
Strategy Pattern
DONE