SlideShare a Scribd company logo
1 of 4
Download to read offline
Solve design problems using Factory Pattern
http://idiotechie.com/?p=480                                                                      July 12, 2012


Factory design pattern is one of the most commonly used patterns in object
oriented environment. It is again from the Creational Design pattern category i.e. all
about object creation.

There are certain cases where the object creation is complex and might require some
level of abstraction so that the client code is unaware of these complexities and


                                                          ie. com
internal implementation details. There might be scenarios where object creation is
scattered and repetitive in various parts of the code.The Factory pattern resolves these issues by

                                                  ech
defining an interface which specifically creates the object but gives the flexibility to the implementation

                                               ot
classes to decide on which class to instantiate.


                                      :// idi
                              tttopdefine an interface for creating objects but
 Definition:
                            h
 The Factory method pattern is
                      ©
 delegates the object creation to the subclasses.


Objective:
Looking at the problem statement the objective should be:

        Client should be unaware of the object instantiation
        Client should access the objects through a common interface.


 Do you know?

 Factory method design pattern is commonly used in various frameworks such as
 Struts, Spring, Apache in conjunction with decorator design pattern. There are
 various J2EE patterns which are based on this Factory pattern e.g. DAO pattern.


Which principle of Object Oriented Design is used in Factory pattern?
Encapsulation : because it encapsulates the creation code from the client. And obviously you can then
think that the benefits of encapsulation are also applicable for this pattern like loose coupling and
cohesion.

Practical Example:
Consider a Garment Factory which produces various types of garments like shirt, trousers. The
consumers can request for the required types of garments through the factory. However from
consumer’s perspective they are completely unaware of who is creating this object. They just know that
the Factory is providing them the required garments.

Problem Statement:
It is a standard practice that objects are created by calling the “new” keyword. Imagine a scenario that
there are multiple cases in the client class and we call multiple new keywords for creating new objects.
if (selection.equalsIgnoreCase("Trouser")) {
return new Trouser();
  } else if (selection.equalsIgnoreCase("Shirt")) {
    return new Shirt();
  }

If we now have to add jacket or sweater we have to keep on modifying the client code and further add
the new keyword. This creates a dependency on the client code and in turn makes it difficult to
maintain.

Another problem is that the client application has to know how many types of concrete classes are

                                                            com
available upfront. Later if we have to add another concrete class e.g. sweater or jacket then client code
has to be changed and recompiled.
                                                        ie.
                                                ech
Solution:

                                             ot
To resolve above problems factory pattern can be used explicitly.

                                        idi
     The first problem of accessing too many new keyword can be resolved by using a Factory class.
                                    ://
                            h ttp
     The second problem can be solved by using an interface which the concrete classes will
     implement and the client will always point to the interface class rather than the concrete classes.
                       ©
     So in this way client will be completely unaware of various types of concrete classes which will be
     required.


 What is an interface?

 An Interfacein Java is a collection of method definitions without implementation.
 The class which implements the interface has to provides the implementation and
 must implement all the methods described in the interface. The interface is a
 contract which tells the classes what to be done leaves it for the classes to decide
 on how they can be implemented.
 interface Bounceable {
       void setBounce();
 }



The below class diagram will give a complete overview of implementation of Factory Pattern:

Let’s take a look at the sample code to implement
Let’s take a look at the sample code to implement
the Factory Pattern:


 GarmentType.java
 public interface GarmentType {
   String print();
 }




                                                    ie. com
                                           ot ech
                                  :// idi                Factory Pattern Class Diagram



 Trouser.java              h ttp
                      ©
 public class Trouser implements GarmentType {
  @Override
  public String print() {
    System.out.println("Trouser Created");
    return "Trouser";
  }

 }




 Shirt.java
 public class Shirt implements GarmentType {
   @Override
   public String print() {
     System.out.println("Shirt Created");
     return "Shirt";
   }
 }




 GarmentFactory.java
 public class GarmentFactory {
   public static GarmentType createGarments(String selection) {
     if (selection.equalsIgnoreCase("Trouser")) {
       return new Trouser();
     } else if (selection.equalsIgnoreCase("Shirt")) {
       return new Shirt();
     }
     throw new IllegalArgumentException("Selection doesnot exist");
   }
 }




 Client.java
public class Client {
   public static void main(String[] args) {
     System.out.println("Enter your selection:");
     BufferedReader br = new BufferedReader(new
 InputStreamReader(System.in));
     String selection = null;
     try {
       selection = br.readLine();
     } catch (IOException e) {
       e.printStackTrace();


                                                              com
     }
     GarmentType objGarmentType =

                                                          ie.
 GarmentFactory.createGarments(selection);


                                                  ech
     System.out.println(objGarmentType.print());
   }
 }
                                               ot
                                     :// idi
Advantage of Factory Pattern:
                             h ttp
a)This client does not need to know about the subclass of objects which requires to be created. It
                       ©
requires the reference to the interface and the factory object.
b)The object creation processes are taken away from the client to the factory and thereby decoupling
the client code with the object creation code. This in turn will help in reusability as this code can be
used by other clients.
c)The Factory pattern also helps in the scalability of the application as the client code only refers to the
interface and we can add more products implementing the interface without making many changes in
the client code.
d)Code maintainability is a beneficial if the application uses Factory pattern as the object creation is
centralized.

More Related Content

Recently uploaded

Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Hiroshi SHIBATA
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfFIDO Alliance
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 

Recently uploaded (20)

Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Idiotechie.com solve design problems using factory pattern

  • 1. Solve design problems using Factory Pattern http://idiotechie.com/?p=480 July 12, 2012 Factory design pattern is one of the most commonly used patterns in object oriented environment. It is again from the Creational Design pattern category i.e. all about object creation. There are certain cases where the object creation is complex and might require some level of abstraction so that the client code is unaware of these complexities and ie. com internal implementation details. There might be scenarios where object creation is scattered and repetitive in various parts of the code.The Factory pattern resolves these issues by ech defining an interface which specifically creates the object but gives the flexibility to the implementation ot classes to decide on which class to instantiate. :// idi tttopdefine an interface for creating objects but Definition: h The Factory method pattern is © delegates the object creation to the subclasses. Objective: Looking at the problem statement the objective should be: Client should be unaware of the object instantiation Client should access the objects through a common interface. Do you know? Factory method design pattern is commonly used in various frameworks such as Struts, Spring, Apache in conjunction with decorator design pattern. There are various J2EE patterns which are based on this Factory pattern e.g. DAO pattern. Which principle of Object Oriented Design is used in Factory pattern? Encapsulation : because it encapsulates the creation code from the client. And obviously you can then think that the benefits of encapsulation are also applicable for this pattern like loose coupling and cohesion. Practical Example: Consider a Garment Factory which produces various types of garments like shirt, trousers. The consumers can request for the required types of garments through the factory. However from consumer’s perspective they are completely unaware of who is creating this object. They just know that the Factory is providing them the required garments. Problem Statement: It is a standard practice that objects are created by calling the “new” keyword. Imagine a scenario that there are multiple cases in the client class and we call multiple new keywords for creating new objects. if (selection.equalsIgnoreCase("Trouser")) {
  • 2. return new Trouser(); } else if (selection.equalsIgnoreCase("Shirt")) { return new Shirt(); } If we now have to add jacket or sweater we have to keep on modifying the client code and further add the new keyword. This creates a dependency on the client code and in turn makes it difficult to maintain. Another problem is that the client application has to know how many types of concrete classes are com available upfront. Later if we have to add another concrete class e.g. sweater or jacket then client code has to be changed and recompiled. ie. ech Solution: ot To resolve above problems factory pattern can be used explicitly. idi The first problem of accessing too many new keyword can be resolved by using a Factory class. :// h ttp The second problem can be solved by using an interface which the concrete classes will implement and the client will always point to the interface class rather than the concrete classes. © So in this way client will be completely unaware of various types of concrete classes which will be required. What is an interface? An Interfacein Java is a collection of method definitions without implementation. The class which implements the interface has to provides the implementation and must implement all the methods described in the interface. The interface is a contract which tells the classes what to be done leaves it for the classes to decide on how they can be implemented. interface Bounceable { void setBounce(); } The below class diagram will give a complete overview of implementation of Factory Pattern: Let’s take a look at the sample code to implement
  • 3. Let’s take a look at the sample code to implement the Factory Pattern: GarmentType.java public interface GarmentType { String print(); } ie. com ot ech :// idi Factory Pattern Class Diagram Trouser.java h ttp © public class Trouser implements GarmentType { @Override public String print() { System.out.println("Trouser Created"); return "Trouser"; } } Shirt.java public class Shirt implements GarmentType { @Override public String print() { System.out.println("Shirt Created"); return "Shirt"; } } GarmentFactory.java public class GarmentFactory { public static GarmentType createGarments(String selection) { if (selection.equalsIgnoreCase("Trouser")) { return new Trouser(); } else if (selection.equalsIgnoreCase("Shirt")) { return new Shirt(); } throw new IllegalArgumentException("Selection doesnot exist"); } } Client.java
  • 4. public class Client { public static void main(String[] args) { System.out.println("Enter your selection:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String selection = null; try { selection = br.readLine(); } catch (IOException e) { e.printStackTrace(); com } GarmentType objGarmentType = ie. GarmentFactory.createGarments(selection); ech System.out.println(objGarmentType.print()); } } ot :// idi Advantage of Factory Pattern: h ttp a)This client does not need to know about the subclass of objects which requires to be created. It © requires the reference to the interface and the factory object. b)The object creation processes are taken away from the client to the factory and thereby decoupling the client code with the object creation code. This in turn will help in reusability as this code can be used by other clients. c)The Factory pattern also helps in the scalability of the application as the client code only refers to the interface and we can add more products implementing the interface without making many changes in the client code. d)Code maintainability is a beneficial if the application uses Factory pattern as the object creation is centralized.