SlideShare a Scribd company logo
Design Patterns
Factory
Flyweight
Singleton
Observer
Proxy
Decorator
What Are Design Patterns?
A solution to a language
independent OO Problem.
If the solution is a
reoccurring over time, it
becomes a “Pattern”.
.net
Java
C++
C#
VB.net
Factory Pattern
Definition
The Factory pattern provides a way to use an instance as a object
factory. The factory can return an instance of one of several possible
classes (in a subclass hierarchy), depending on the data provided to
it.
Where to use
1) When a class can't anticipate which kind of class of object it must
create.
2) You want to localize the knowledge of which class gets created.
3) When you have classes that is derived from the same subclasses,
or they may in fact be unrelated classes that just share the same
interface. Either way, the methods in these class instances are the
same and can be used interchangeably.
4) When you want to insulate the client from the actual type that is
being instantiated.
Factory PatternClass Diagram
Factory Patternpublic abstract class Product {
public void writeName(String name) {
System.out.println("My name is "+name);
}
}
public class ProductA extends Product { }
public class ProductB extends Product {
public void writeName(String name) {
StringBuilder tempName = new StringBuilder().append(name);
System.out.println("My reversed name is" + tempName.reverse());
}
}
public class ProductFactory {
public Product createProduct(String type) {
if(type.equals("B"))
return new ProductB();
else
return new ProductA();
}
}
ProductFactory pf = new ProductFactory();
Product prod;
prod = pf.createProduct("A");
prod.writeName("John Doe");
prod = pf.createProduct("B");
prod.writeName("John Doe");
Connection, Statement, ResultSet
Proxy Pattern
DefinitionDefinition
A Proxy is a structural pattern that provides a stand-in for
another object in order to control access to it.
Where to useWhere to use
1) When the creation of one object is relatively expensive it can be a
good idea to replace it with a proxy that can make sure that
instantiation of the expensive object is kept to a minimum.
2) Proxy pattern implementation allows for login and authority
checking before one reaches the actual object that's requested.
3) Can provide a local representation for an object in a remote
location.
Proxy PatternClass Diagram
Proxy Patterninterface IExploded {
public void pumpPetrol(String arg);
}
class ProxyExploded implements IExploded{
public void pumpPetrol(String arg){
System.out.println("Pumping. ");
}
}
public class Pattern_Proxy implements IExploded
{
StringBuffer strbuf = new StringBuffer();
public void pumpPetrol(String arg){
strbuf.append(arg);
System.out.println("Pumping. ");
if(strbuf.length() >70){
explosion2(); strbuf.delete(0, strbuf.length()); System.exit(0);
}else if(strbuf.length()>50){
explosion1();
}
}
public void explosion1(){ System.out.println("System is about to Explode"); }
public void explosion2(){
System.out.println("System has exploded... Kaboom!!.. rn”+
”To Much Petrol.."+strbuf.length()+" L");
}
}
public static void main(String arg[])
{
IExploded prox = new Pattern_Proxy();
for(int y=0; y<50; y++){
prox.pumpPetrol("Petrol.");
}
}
Singleton Pattern
Definition
The Singleton pattern provides the possibility to control the
number of instances (mostly one) that are allowed to be
made. We also receive a global point of access to it (them).
Where to use
When only one instance or a specific number of instances of
a class are allowed. Facade objects are often Singletons
because only one Facade object is required.
Benefits
•Controlled access to unique instance.
•Reduced name space.
•Allows refinement of operations and representations.
Class Diagram
Singleton Pattern
Singleton Pattern
public class MapLogger
{
private static MapLogger mapper=null;
// Prevent clients from using the constructor
private MapLogger() { /* Nothing Here :-) */ }
//Control the accessible (allowed) instances
public static MapLogger getMapLogger() {
if (mapper == null) {
mapper = new MapLogger();
}
return mapper;
}
public synchronized void put(String key, String val)
{
// Write to Map/Hashtable...
}
}
Flyweight Pattern
Definition
The Flyweight pattern provides a mechanism by which you can
avoid creating a large number of 'expensive' objects and instead
reuse existing instances to represent new ones.
Where to use
1) When there is a very large number of objects that may not fit in
memory.
2) When most of an objects state can be stored on disk or calculated
at Runtime.
3) When there are groups of objects that share state.
4) When the remaining state can be factored into a much smaller
number of objects with shared state.
Benefits
Reduce the number of objects created, decrease memory footprint
and increase performance.
Flyweight Pattern
Flyweight Patternclass Godzilla {
private int row;
public Godzilla( int theRow ) {
row = theRow;
System.out.println( "ctor: " + row );
}
void report( int theCol ) {
System.out.print( " " + row + theCol );
}
} class Factory {
private Godzilla[] pool;
public Factory( int maxRows ) {
pool = new Godzilla[maxRows];
}
public Godzilla getFlyweight( int theRow ) {
if (pool[theRow] == null)
pool[theRow] = new Godzilla( theRow );
return pool[theRow];
}
}
public class FlyweightDemo {
public static final int ROWS = 6, COLS = 10;
public static void main( String[] args ) {
Factory theFactory = new Factory( ROWS );
for (int i=0; i < ROWS; i++) {
for (int j=0; j < COLS; j++)
theFactory.getFlyweight( i ).report( j );
System.out.println();
} } }
Observer Pattern
Definition
Proxy pattern is a behavioral pattern. It defines a one-to-many
dependency between objects, so that when one object changes its
state, all its dependent objects are notified and updated.
Where to use
1) When state changes of a one object must be reflected in other
objects without depending on the state changing process of the object
(reduce the coupling between the objects).
Observer Pattern
Observer Pattern
public class WeatherStation extends Observable implements Runnable {
public void run() {
String report = this.getCurrentReport();
notifyObservers( report );
}
}
public class WeatherObserver implements Observer {
private String response;
public void update (Observable obj, Object arg) {
response = (String)arg;
}
}
Observer Pattern
public class WeatherClient {
public static void main(String args[]) {
// create a WheatherStation instance
final WeatherStation station = new WeatherStation();
// create an observer
final WeatherObserver weatherObserver = new WeatherObserver();
// subscribe the observer to the event source
station.addObserver( weatherObserver );
// starts the event thread
Thread thread = new Thread(station);
thread.start();
}
}
Decorator Pattern
Definition
Decorator pattern is a structural pattern. Intent of the pattern is to add
additional responsibilities dynamically to an object.
Where to use
1) When you want the responsibilities added to or removed from an
object at runtime.
2) When using inheritance results in a large number of subclasses.
Decorator Pattern
Decorator Pattern
// The Coffee Interface defines the functionality of Coffee implemented by
decorator
public interface Coffee {
// returns the cost of the coffee
public double getCost();
// returns the ingredients of the coffee
public String getIngredients();
}
// implementation of a simple coffee without any extra ingredients
public class SimpleCoffee implements Coffee {
public double getCost() {
return 1;
}
public String getIngredients() {
return "Coffee";
}
}
Decorator Pattern
// abstract decorator class - note that it implements Coffee interface
abstract public class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;
protected String ingredientSeparator = ", ";
public CoffeeDecorator(Coffee decoratedCoffee) {
this.decoratedCoffee = decoratedCoffee;
}
public double getCost() {
// implementing methods of the interface
return decoratedCoffee.getCost();
}
public String getIngredients() {
return decoratedCoffee.getIngredients();
}
}
Decorator Pattern
// Decorator Milk that mixes milk with coffee
// note it extends CoffeeDecorator
public class Milk extends CoffeeDecorator {
public Milk(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
// overriding methods defined in the abstract superclass
return super.getCost() + 0.5;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Milk";
}
}
Decorator Pattern
public class Whip extends CoffeeDecorator {
public Whip(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.7;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Whip";
}
}
Decorator Pattern
public class CoffeMaker {
public static void main(String[] args) {
Coffee c = new SimpleCoffee();
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new Milk(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
}
}
Decorator Pattern
public class Whip extends CoffeeDecorator {
public Whip(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.7;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Whip";
}
}

More Related Content

What's hot (20)

PPTX
Object Oriented Programming Using C++
Muhammad Waqas
 
PPTX
[OOP - Lec 01] Introduction to OOP
Muhammad Hammad Waseem
 
PDF
Templates
Pranali Chaudhari
 
PDF
What is Python Lambda Function? Python Tutorial | Edureka
Edureka!
 
PDF
Python recursion
Prof. Dr. K. Adisesha
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PDF
Remote Method Invocation (RMI)
Peter R. Egli
 
PPTX
Python-Classes.pptx
Karudaiyar Ganapathy
 
PPTX
Getters_And_Setters.pptx
Kavindu Sachinthe
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPTX
OOP - Polymorphism
Mudasir Qazi
 
PPT
JDBC Architecture and Drivers
SimoniShah6
 
PDF
Access specifiers (Public Private Protected) C++
vivekkumar2938
 
PPTX
Code Generation
PrabuPappuR
 
DOCX
2nd mid term daa paper
Mansi Puri
 
PPTX
object oriented Programming ppt
Nitesh Dubey
 
PPTX
Friend Function
Mehak Tawakley
 
PPT
Recursion.ppt
TalhaHussain58
 
PPT
Files and Directories in PHP
Nicole Ryan
 
PPT
Oops ppt
abhayjuneja
 
Object Oriented Programming Using C++
Muhammad Waqas
 
[OOP - Lec 01] Introduction to OOP
Muhammad Hammad Waseem
 
What is Python Lambda Function? Python Tutorial | Edureka
Edureka!
 
Python recursion
Prof. Dr. K. Adisesha
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Remote Method Invocation (RMI)
Peter R. Egli
 
Python-Classes.pptx
Karudaiyar Ganapathy
 
Getters_And_Setters.pptx
Kavindu Sachinthe
 
Functions in c++
Rokonuzzaman Rony
 
OOP - Polymorphism
Mudasir Qazi
 
JDBC Architecture and Drivers
SimoniShah6
 
Access specifiers (Public Private Protected) C++
vivekkumar2938
 
Code Generation
PrabuPappuR
 
2nd mid term daa paper
Mansi Puri
 
object oriented Programming ppt
Nitesh Dubey
 
Friend Function
Mehak Tawakley
 
Recursion.ppt
TalhaHussain58
 
Files and Directories in PHP
Nicole Ryan
 
Oops ppt
abhayjuneja
 

Viewers also liked (20)

PPTX
The family
tsiribi
 
PDF
Architecting Large Enterprise Java Projects
Markus Eisele
 
PDF
Community and Java EE @ DevConf.CZ
Markus Eisele
 
PDF
Erika Hall - Running, Yoga, + Conditioning Website Wireframe
Erika Martin Hall
 
PPT
Using and Setting Website Sales Goal
Brandwise
 
PPTX
10 Important Tips For Increasing Traffic On Your Website
Eminenture
 
PPTX
E-Bay
Nirma University
 
PPTX
Ebay presentation
Pickevent
 
PPT
java swing
vannarith
 
PDF
eBay inc. Case Study
Chaahat Khattar
 
PPTX
Website analysis and Competitor Analysis and Website Wireframe
Saloni Jain
 
PPTX
Srs present
Vidyas Gnanasekaram
 
PPTX
55 New Features in Java SE 8
Simon Ritter
 
PDF
Online shopping portal: Software Project Plan
piyushree nagrale
 
PPTX
Powerpoint Presentation on eBay.com
myclass08
 
PPT
Sales Interview Presentation
Novin
 
DOC
Onlineshopping
amitesh2690
 
PPT
An interview presentation that lands senior-level jobs
psymar
 
PPTX
Presentation on Amazon
Avinandan Karmakar
 
The family
tsiribi
 
Architecting Large Enterprise Java Projects
Markus Eisele
 
Community and Java EE @ DevConf.CZ
Markus Eisele
 
Erika Hall - Running, Yoga, + Conditioning Website Wireframe
Erika Martin Hall
 
Using and Setting Website Sales Goal
Brandwise
 
10 Important Tips For Increasing Traffic On Your Website
Eminenture
 
Ebay presentation
Pickevent
 
java swing
vannarith
 
eBay inc. Case Study
Chaahat Khattar
 
Website analysis and Competitor Analysis and Website Wireframe
Saloni Jain
 
Srs present
Vidyas Gnanasekaram
 
55 New Features in Java SE 8
Simon Ritter
 
Online shopping portal: Software Project Plan
piyushree nagrale
 
Powerpoint Presentation on eBay.com
myclass08
 
Sales Interview Presentation
Novin
 
Onlineshopping
amitesh2690
 
An interview presentation that lands senior-level jobs
psymar
 
Presentation on Amazon
Avinandan Karmakar
 
Ad

Similar to Java design patterns (20)

PDF
Design patterns
Anas Alpure
 
PPTX
Structural pattern 3
Naga Muruga
 
PDF
Gephi Toolkit Tutorial
Gephi Consortium
 
PPTX
2. Design patterns. part #2
Leonid Maslov
 
PPTX
Presentation.pptx
PavanKumar823345
 
PPTX
Creational pattern 2
Naga Muruga
 
PDF
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
PPTX
A brief overview of java frameworks
MD Sayem Ahmed
 
PDF
Javascript Design Patterns
Subramanyan Murali
 
PDF
Fun Teaching MongoDB New Tricks
MongoDB
 
PDF
Uncommon Design Patterns
Stefano Fago
 
PDF
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
PDF
Overview of Android Infrastructure
Alexey Buzdin
 
PDF
Overview of Android Infrastructure
C.T.Co
 
PPTX
Use of Apache Commons and Utilities
Pramod Kumar
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
PPT
P Training Presentation
Gaurav Tyagi
 
KEY
JavaScript Growing Up
David Padbury
 
DOCX
C questions
parm112
 
Design patterns
Anas Alpure
 
Structural pattern 3
Naga Muruga
 
Gephi Toolkit Tutorial
Gephi Consortium
 
2. Design patterns. part #2
Leonid Maslov
 
Presentation.pptx
PavanKumar823345
 
Creational pattern 2
Naga Muruga
 
Design patterns in Java - Monitis 2017
Arsen Gasparyan
 
A brief overview of java frameworks
MD Sayem Ahmed
 
Javascript Design Patterns
Subramanyan Murali
 
Fun Teaching MongoDB New Tricks
MongoDB
 
Uncommon Design Patterns
Stefano Fago
 
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
C.T.Co
 
Use of Apache Commons and Utilities
Pramod Kumar
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
P Training Presentation
Gaurav Tyagi
 
JavaScript Growing Up
David Padbury
 
C questions
parm112
 
Ad

Recently uploaded (20)

PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Executive Business Intelligence Dashboards
vandeslie24
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Import Data Form Excel to Tally Services
Tally xperts
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 

Java design patterns

  • 2. What Are Design Patterns? A solution to a language independent OO Problem. If the solution is a reoccurring over time, it becomes a “Pattern”. .net Java C++ C# VB.net
  • 3. Factory Pattern Definition The Factory pattern provides a way to use an instance as a object factory. The factory can return an instance of one of several possible classes (in a subclass hierarchy), depending on the data provided to it. Where to use 1) When a class can't anticipate which kind of class of object it must create. 2) You want to localize the knowledge of which class gets created. 3) When you have classes that is derived from the same subclasses, or they may in fact be unrelated classes that just share the same interface. Either way, the methods in these class instances are the same and can be used interchangeably. 4) When you want to insulate the client from the actual type that is being instantiated.
  • 5. Factory Patternpublic abstract class Product { public void writeName(String name) { System.out.println("My name is "+name); } } public class ProductA extends Product { } public class ProductB extends Product { public void writeName(String name) { StringBuilder tempName = new StringBuilder().append(name); System.out.println("My reversed name is" + tempName.reverse()); } } public class ProductFactory { public Product createProduct(String type) { if(type.equals("B")) return new ProductB(); else return new ProductA(); } } ProductFactory pf = new ProductFactory(); Product prod; prod = pf.createProduct("A"); prod.writeName("John Doe"); prod = pf.createProduct("B"); prod.writeName("John Doe"); Connection, Statement, ResultSet
  • 6. Proxy Pattern DefinitionDefinition A Proxy is a structural pattern that provides a stand-in for another object in order to control access to it. Where to useWhere to use 1) When the creation of one object is relatively expensive it can be a good idea to replace it with a proxy that can make sure that instantiation of the expensive object is kept to a minimum. 2) Proxy pattern implementation allows for login and authority checking before one reaches the actual object that's requested. 3) Can provide a local representation for an object in a remote location.
  • 8. Proxy Patterninterface IExploded { public void pumpPetrol(String arg); } class ProxyExploded implements IExploded{ public void pumpPetrol(String arg){ System.out.println("Pumping. "); } } public class Pattern_Proxy implements IExploded { StringBuffer strbuf = new StringBuffer(); public void pumpPetrol(String arg){ strbuf.append(arg); System.out.println("Pumping. "); if(strbuf.length() >70){ explosion2(); strbuf.delete(0, strbuf.length()); System.exit(0); }else if(strbuf.length()>50){ explosion1(); } } public void explosion1(){ System.out.println("System is about to Explode"); } public void explosion2(){ System.out.println("System has exploded... Kaboom!!.. rn”+ ”To Much Petrol.."+strbuf.length()+" L"); } } public static void main(String arg[]) { IExploded prox = new Pattern_Proxy(); for(int y=0; y<50; y++){ prox.pumpPetrol("Petrol."); } }
  • 9. Singleton Pattern Definition The Singleton pattern provides the possibility to control the number of instances (mostly one) that are allowed to be made. We also receive a global point of access to it (them). Where to use When only one instance or a specific number of instances of a class are allowed. Facade objects are often Singletons because only one Facade object is required. Benefits •Controlled access to unique instance. •Reduced name space. •Allows refinement of operations and representations.
  • 11. Singleton Pattern public class MapLogger { private static MapLogger mapper=null; // Prevent clients from using the constructor private MapLogger() { /* Nothing Here :-) */ } //Control the accessible (allowed) instances public static MapLogger getMapLogger() { if (mapper == null) { mapper = new MapLogger(); } return mapper; } public synchronized void put(String key, String val) { // Write to Map/Hashtable... } }
  • 12. Flyweight Pattern Definition The Flyweight pattern provides a mechanism by which you can avoid creating a large number of 'expensive' objects and instead reuse existing instances to represent new ones. Where to use 1) When there is a very large number of objects that may not fit in memory. 2) When most of an objects state can be stored on disk or calculated at Runtime. 3) When there are groups of objects that share state. 4) When the remaining state can be factored into a much smaller number of objects with shared state. Benefits Reduce the number of objects created, decrease memory footprint and increase performance.
  • 14. Flyweight Patternclass Godzilla { private int row; public Godzilla( int theRow ) { row = theRow; System.out.println( "ctor: " + row ); } void report( int theCol ) { System.out.print( " " + row + theCol ); } } class Factory { private Godzilla[] pool; public Factory( int maxRows ) { pool = new Godzilla[maxRows]; } public Godzilla getFlyweight( int theRow ) { if (pool[theRow] == null) pool[theRow] = new Godzilla( theRow ); return pool[theRow]; } } public class FlyweightDemo { public static final int ROWS = 6, COLS = 10; public static void main( String[] args ) { Factory theFactory = new Factory( ROWS ); for (int i=0; i < ROWS; i++) { for (int j=0; j < COLS; j++) theFactory.getFlyweight( i ).report( j ); System.out.println(); } } }
  • 15. Observer Pattern Definition Proxy pattern is a behavioral pattern. It defines a one-to-many dependency between objects, so that when one object changes its state, all its dependent objects are notified and updated. Where to use 1) When state changes of a one object must be reflected in other objects without depending on the state changing process of the object (reduce the coupling between the objects).
  • 17. Observer Pattern public class WeatherStation extends Observable implements Runnable { public void run() { String report = this.getCurrentReport(); notifyObservers( report ); } } public class WeatherObserver implements Observer { private String response; public void update (Observable obj, Object arg) { response = (String)arg; } }
  • 18. Observer Pattern public class WeatherClient { public static void main(String args[]) { // create a WheatherStation instance final WeatherStation station = new WeatherStation(); // create an observer final WeatherObserver weatherObserver = new WeatherObserver(); // subscribe the observer to the event source station.addObserver( weatherObserver ); // starts the event thread Thread thread = new Thread(station); thread.start(); } }
  • 19. Decorator Pattern Definition Decorator pattern is a structural pattern. Intent of the pattern is to add additional responsibilities dynamically to an object. Where to use 1) When you want the responsibilities added to or removed from an object at runtime. 2) When using inheritance results in a large number of subclasses.
  • 21. Decorator Pattern // The Coffee Interface defines the functionality of Coffee implemented by decorator public interface Coffee { // returns the cost of the coffee public double getCost(); // returns the ingredients of the coffee public String getIngredients(); } // implementation of a simple coffee without any extra ingredients public class SimpleCoffee implements Coffee { public double getCost() { return 1; } public String getIngredients() { return "Coffee"; } }
  • 22. Decorator Pattern // abstract decorator class - note that it implements Coffee interface abstract public class CoffeeDecorator implements Coffee { protected final Coffee decoratedCoffee; protected String ingredientSeparator = ", "; public CoffeeDecorator(Coffee decoratedCoffee) { this.decoratedCoffee = decoratedCoffee; } public double getCost() { // implementing methods of the interface return decoratedCoffee.getCost(); } public String getIngredients() { return decoratedCoffee.getIngredients(); } }
  • 23. Decorator Pattern // Decorator Milk that mixes milk with coffee // note it extends CoffeeDecorator public class Milk extends CoffeeDecorator { public Milk(Coffee decoratedCoffee) { super(decoratedCoffee); } public double getCost() { // overriding methods defined in the abstract superclass return super.getCost() + 0.5; } public String getIngredients() { return super.getIngredients() + ingredientSeparator + "Milk"; } }
  • 24. Decorator Pattern public class Whip extends CoffeeDecorator { public Whip(Coffee decoratedCoffee) { super(decoratedCoffee); } public double getCost() { return super.getCost() + 0.7; } public String getIngredients() { return super.getIngredients() + ingredientSeparator + "Whip"; } }
  • 25. Decorator Pattern public class CoffeMaker { public static void main(String[] args) { Coffee c = new SimpleCoffee(); System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients()); c = new Milk(c); System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients()); } }
  • 26. Decorator Pattern public class Whip extends CoffeeDecorator { public Whip(Coffee decoratedCoffee) { super(decoratedCoffee); } public double getCost() { return super.getCost() + 0.7; } public String getIngredients() { return super.getIngredients() + ingredientSeparator + "Whip"; } }