Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Template Method | JavaScript Design Patterns
Next article icon

Abstract Factory Pattern | JavaScript Design Patterns

Last Updated : 30 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects.

Important Topics for the Abstract Factory Pattern in JavaScript Design Patterns

  • Example of Abstract Method in JavaScript Design Patterns
  • Advantages of the Abstract Factory Pattern
  • Disadvantages of the Abstract Factory Pattern
  • Conclusion

Example of Abstract Method in JavaScript Design Patterns:

Imagine, we're building a UI component library that supports multiple themes (e.g., light and dark themes). We want to create sets of UI components like buttons, input fields, and tooltips for each theme.

Below is the implementation of the above example:

JavaScript
// Abstract factory for creating UI components class UIFactory {   createButton() {}   createInputField() {}   createTooltip() {} }  // Concrete factory for light theme components class LightThemeFactory extends UIFactory {   createButton() {     return new LightThemeButton();   }   createInputField() {     return new LightThemeInputField();   }   createTooltip() {     return new LightThemeTooltip();   } }  // Concrete factory for dark theme components class DarkThemeFactory extends UIFactory {   createButton() {     return new DarkThemeButton();   }   createInputField() {     return new DarkThemeInputField();   }   createTooltip() {     return new DarkThemeTooltip();   } }  // Abstract product for buttons class Button {}  // Concrete product for light theme buttons class LightThemeButton extends Button {   constructor() {     super();     console.log('Light theme button created');   } }  // Concrete product for dark theme buttons class DarkThemeButton extends Button {   constructor() {     super();     console.log('Dark theme button created');   } }  // Usage const lightFactory = new LightThemeFactory(); const lightButton = lightFactory.createButton(); // Output: Light theme button created  const darkFactory = new DarkThemeFactory(); const darkButton = darkFactory.createButton(); // Output: Dark theme button created 

Output
Light theme button created Dark theme button created

Key components of Abstract factory Pattern

  • Abstract Factory: This is an interface or an abstract class that declares a set of factory methods for creating a family of related objects.
  • Concrete Factory: These are the implementations of the abstract factory interface. Each concrete factory is responsible for creating a specific family of related objects.
  • Abstract Products: These are interfaces or abstract classes that declare the common set of methods for the objects within a family.
  • Concrete Products: These are the actual implementations of the abstract products. Each concrete product is specific to a particular family and is created by a corresponding concrete factory.
  • Client: The client code interacts with the abstract factory and abstract product interfaces.

Step wise Code understanding by taking Key Component

Abstarct Factory: Implement an abstract factory, UIFactory, that defines the blueprint for creating UI components.

JavaScript
// Abstract factory for creating UI components class UIFactory {   createButton() {}   createInputField() {}   createTooltip() {} } 


Concrete Factory: Create concrete factories for different themes: LightThemeFactory and DarkThemeFactory, each inheriting from the UIFactory.

JavaScript
// Concrete factory for light theme components class LightThemeFactory extends UIFactory {   createButton() {     return new LightThemeButton();   }   createInputField() {     return new LightThemeInputField();   }   createTooltip() {     return new LightThemeTooltip();   } } 
JavaScript
//Concrete factory for dark theme components class DarkThemeFactory extends UIFactory {   createButton() {     return new DarkThemeButton();   }   createInputField() {     return new DarkThemeInputField();   }   createTooltip() {     return new DarkThemeTooltip();   } } 


Abstract Product: Define abstract product classes for various UI components, such as Button.

JavaScript
// Abstract product for buttons class Button {} 


Concrete Product: Create concrete product classes, such as LightThemeButton and DarkThemeButton, that inherit from the abstract product classes.

JavaScript
// Concrete product for light theme buttons class LightThemeButton extends Button {   constructor() {     super();     console.log('Light theme button created');   } } 
JavaScript
// Concrete product for dark theme buttons class DarkThemeButton extends Button {   constructor() {     super();     console.log('Dark theme button created');   } } 

When a UI component is created, it should log a message indicating which theme it belongs to. For example, a button created by the light theme factory should display "Light theme button created."

Abstract Factory Pattern allows us to create entire families of related objects that are compatible with each other. The client code remains unaware of the specific implementations.

Advantages of the Abstract Factory Pattern

  • Consistency: Abstract factories patterns ensure that the objects created within a family are compatible with each other. This helps us to maintain the consistency in our application, as we can ensure that all the objects created by the factory work together.
  • Flexibility: Abstract Factory pattern allows us to switch between different families of objects by using different concrete factories. This is especially useful when we need to support multiple variations of a product or when we want to change the behavior of our application by swapping out factories at runtime.
  • Extensibility: Basically, we can add new concrete factories to support new product families without modifying existing client code. This makes the system more extensible, allowing for the easy addition of new features or components.
  • Testability: Abstract factories patterns make it very easier to write unit tests and mock objects. By creating a factory interface, we can simply create mock or test-specific implementations to facilitate testing without affecting the rest of our code.
  • Encapsulation of Object Creation: Abstract Factory pattern encapsulates the creation of objects. This means that the client code does not need to be aware of the specific classes it is instantiating, promoting loose coupling between the client and the concrete objects.

Disadvantages of the Abstract Factory Pattern

  • Tight Coupling: Suppose if we needs to add new products or make changes to existing ones, than we need to modify both the abstract factory interface and the concrete factory implementations. This can lead to tight coupling between the factories and their products, potentially violating the Open-Closed Principle.
  • Increased Complexity: We need to define interfaces for factories and their product families, create concrete factory implementations, and manage the relationships between factories and products.
  • Code Duplication: While implementing concrete factories patterns for different product families, we end up with duplicate code for creating similar types of objects across multiple factories.
  • Reduced Runtime Flexibility: Once we choose a concrete factory to create objects, it is typically challenging to switch to a different factory at runtime. This limitation can restrict your ability to adapt to changing requirements dynamically.
  • Limited Use Cases: Abstract Factory pattern is most valuable in scenarios where there are multiple related product families with interchangeable components. In simpler applications, the overhead of implementing and maintaining factories may not be justified.

Conclusion

Abstract Factory Pattern promotes the creation of families of related objects while keeping the code decoupled, maintainable, and adaptable to changing requirements or platforms. It's a powerful tool for managing object creation in complex systems.


Next Article
Template Method | JavaScript Design Patterns
author
aakashattri111
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023
  • JavaScript Design Patterns

Similar Reads

  • JavaScript Design Patterns Tutorial
    Design patterns in Javascipt are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best
    8 min read
  • Creational Software Design Patterns in JavaScript

    • Builder Method | JavaScript Design Pattern
      The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pa
      9 min read
    • Prototype Method - JavaScript Design Pattern
      A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance
      3 min read
    • Abstract Factory Pattern | JavaScript Design Patterns
      Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface
      6 min read
    • Behavioural Software Design Patterns in JavaScript

      • Template Method | JavaScript Design Patterns
        Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure
        10 min read
      • State Method Design Patterns in JavaScript
        State method or State Design Patterns is a pattern that allows an object to alter its behavior when internal state changes occur. This pattern is used when an object wants to change its state dynamically. When we want to change behavior of object it internally uses if-else block to perform actions.
        4 min read
      • Iterator Method | JavaScript Design Pattern
        Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is wi
        4 min read
      • Strategy Method | JavaScript Design Pattern
        Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes t
        8 min read
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences