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:
Flyweight Design Pattern - JavaScript Design Pattern
Next article icon

Factory Method in JavaScript | Design Pattern

Last Updated : 29 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Factory Design Pattern is a creational pattern that allows for the creation of objects without exposing the creation logic to the client. It involves creating a separate factory function that is responsible for creating instances of various related objects based on a specified input. In modern software development, the Factory Design Pattern plays a crucial role in creating objects while abstracting away the specifics of their creation. In JavaScript, we can implement this pattern using factory functions.

Important Topics of Factory Method in Javascript Design Pattern

  • Example of Factory Method in JavaScript Design Pattern
  • Advantages of Factory Method in JavaScript Design Pattern
  • Disadvantages of Factory Method in JavaScript Design Pattern

Example of Factory Method in JavaScript Design Pattern

Below is an example of the Factory Method in JavaScript Design Pattern:

JavaScript
// Factory function to create a user based on role and user info const createUser = (role, userInfo) => {   // Initialize a user object with common properties   const user = {     name: userInfo.name,     password: userInfo.password   };    // Define specific additional information based on the role   const specificInfo = {     admin: () => ({ role: 'Admin', key: userInfo.key }),     customer: () => ({ role: 'Customer', address: userInfo.address }),     seller: () => ({ role: 'Seller', shopAddress: userInfo.shopAddress, contact_No: userInfo.contact_No })   };    // Get additional information based on the role provided   const additionalInfo = specificInfo[role] ? specificInfo[role]() : null;    // If an invalid role was specified, throw an error   if (!additionalInfo) {     throw new Error('Invalid role specified.');   }    // Combine the common user properties with additional role-specific properties   return { ...user, ...additionalInfo }; };  // Create an Admin User instance const adminUser = createUser('admin', {   name: 'Abhishek',   password: 'Abhi1233',   key: '#1244534-fadsv34' });  // Create a Customer User instance const customerUser = createUser('customer', {   name: 'John Doe',   password: 'Password123',   address: '123 Main St' });  // Create a Seller User instance const sellerUser = createUser('seller', {   name: 'Jane Smith',   password: 'SellerPass',   shopAddress: '456 Market St',   contact_No: '123-456-7890' });  // Log the Admin User details console.log('Admin User:', adminUser);  // Log the Customer User details console.log('Customer User:', customerUser);  // Log the Seller User details console.log('Seller User:', sellerUser); 


Output:

Admin User: {

name: 'Abhishek'
password: 'Abhi1233',
role: 'Admin',
key: '#1244534-fadsv34'

}

Customer User: {

name: 'John Doe',
password: 'Password123',
role: 'Customer',
address: '123 Main St'

}

Seller User: {

name: 'Jane Smith',
password: 'SellerPass',
role: 'Seller',
shopAddress: '456 Market St',
contact_No: '123-456-7890'

}

Explanation:

const createUser = (role, userInfo) => {

const user = {

name: userInfo.name,
password: userInfo.password

};

Here, we have a function createUser this function is called factory function (CONSTRUCTOR PATTERN FUNCTION).

The Constructor Pattern, on the other hand, is used to create multiple instances of an object. It’s the JavaScript’s way of creating an instance of an object.

Factory Function createUser:

  • Parameters: role (represents the user role, e.g., 'admin', 'customer', 'seller') and userInfo (an object containing user-specific information like name, password, etc.).
  • Common User Object: A user object is created with common properties (name and password) taken from the userInfo object.

Role-Specific Information:

  • specificInfo Object: Acts as a lookup table where each role (admin, customer, or seller) is associated with a function returning an object with role-specific information based on the provided userInfo.
  • Role Functions: Each function returns additional properties specific to the role (e.g., key for admin, address for customer, shopAddress and contact_No for seller).

Here, we have a function createUser this function is called factory function.
It takes two parameters:

  • Role (representing the user role, e.g., 'admin', 'customer', 'seller')
  • userInfo (an object containing user-specific information like name, password, etc.).

Inside this function, we start by creating a user object with common properties, name and password, taken from the userInfo object.

const specificInfo = {

admin: () => ({ role: 'Admin', key: userInfo.key }),

customer: () => ({ role: 'Customer', address: userInfo.address }),

seller: () => ({ role: 'Seller', shopAddress: userInfo.shopAddress, contact_No: userInfo.contact_No })

};

Here we define a specificInfo object. It serves as a lookup table where each role (admin, customer, or seller) is associated with a function. These functions return an object with role-specific information based on the provided userInfo.

  • For the 'admin' role, the function returns an object with a role of 'Admin' and includes a 'key' based on the provided userInfo.
  • For the 'customer' role, the function returns an object with a role of 'Customer' and includes an 'address' based on the provided userInfo.
  • For the 'seller' role, the function returns an object with a role of 'Seller' and includes 'shopAddress' and 'contact_No' based on the provided userInfo.

This structure allows for role-specific handling of user information, ensuring that each user type (admin, customer, or seller) gets the appropriate properties set based on their role.

const additionalInfo = specificInfo[role] ? specificInfo[role]() : null;

Here, we use the role parameter to retrieve the corresponding function from the specificInfo object. If the role is valid, we call the corresponding function to get the additional role-specific information. If the role is invalid, it returns null.

if (!additionalInfo) {

throw new Error('Invalid role specified.');

}

Here, we check if additionalInfo is null. If it's null, we throw an error using throw new Error().

return { ...user, ...additionalInfo };

Finally, if the role is valid, we combine the common user properties (name and password) with the additional role-specific properties using the spread operator

({ ...user, ...additionalInfo }).

This creates a new object that represents the user with all the appropriate properties based on the specified role, and we return it.

The createUser function essentially acts as a factory, creating a user object based on the provided role and user information.

const adminUser = createUser('admin', {

name: 'Abhishek',
password: 'Abhi1233',
key: '#1244534-fadsv34'

});

const customerUser = createUser('customer', {

name: 'John Doe',
password: 'Password123',
address: '123 Main St'

});

const sellerUser = createUser('seller', {

name: 'Jane Smith',
password: 'SellerPass',
shopAddress: '456 Market St',
contact_No: '123-456-7890'

});

using createUser function to create different type of user according to there role.

console.log('Admin User:', adminUser);

console.log('Customer User:', customerUser);

console.log('Seller User:', sellerUser);

The user information for each type is logged to the console.

Advantages of Factory Method in JavaScript Design Pattern

  • Abstraction and Encapsulation: The factory function encapsulates the logic for creating objects based on role, abstracting away the creation details. Users of the factory don't need to worry about the intricate creation process.
  • Simplified Object Creation: The factory pattern simplifies object creation. Users only need to call a function, passing the necessary parameters, to get a fully initialized object.
  • Flexibility and Extensibility: The factory can easily accommodate changes and additions of new user roles. Adding a new role is a matter of extending the specific information and adding a function to the specificInfo object.
  • Code Reusability: The creation logic is centralized in the factory function, allowing for reusability across the application. Users can be created consistently wherever needed.
  • Enhanced Readability and Maintainability: The factory pattern improves code readability by abstracting the object creation process. It's easier to understand the intent of creating a specific type of user by calling a function with a role.
  • Error Handling: The factory can provide structured error handling, ensuring that users adhere to specific roles and fail gracefully with meaningful error messages.

Disadvantages of Factory Method in JavaScript Design Pattern

  • Complexity for Simple Cases: For simple cases where the object creation logic is straightforward, using a factory might introduce unnecessary complexity. Direct object creation might be more appropriate for such scenarios.
  • Potential Performance Overheads: The additional function calls and lookup operations in the factory can introduce a minor performance overhead compared to direct object creation. However, in most cases, this overhead is negligible.
  • Understanding the Factory Logic: For someone unfamiliar with the factory pattern, understanding the role of each function and how the factory creates objects might take some time.
  • Dependency on External Configuration: The factory relies on external configurations (like the specificInfo object) to determine object creation. If these configurations are modified or incorrect, it can lead to unexpected behavior.
  • Potential Overuse: Overuse of the factory pattern can lead to an overly complex codebase, making it harder to understand and maintain. It's important to use the pattern judiciously and where it provides clear benefits.

Next Article
Flyweight Design Pattern - JavaScript Design Pattern

A

abhisheksahu20010525
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