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:
Abstract Factory Pattern | C++ Design Patterns
Next article icon

Factory Method Pattern | C++ Design Patterns

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

Factory Method Pattern provides an interface for creating objects but leaves the actual object instantiation to derived classes. This allows for flexibility in object creation and promotes loose coupling between the client code and the concrete products.

Factory-Design-Pattern-in-C-plus-plus
Factory Method Pattern | C++ Design Patterns

Table of Content

  • What is the Factory Method Design Pattern?
  • Core Components of the Factory Method
  • Implementation of the Factory Method in C++
  • Use Cases of the Factory Method
  • Advantages of the Factory Method
  • Disadvantages of the Factory Method
  • When to Use the Factory Method
  • When Not to Use the Factory Method

What is the Factory Method Design Pattern?

The Factory Method Design Pattern is a creational design pattern used in software development. It provides an interface for creating objects in a superclass while allowing subclasses to specify the types of objects they create.

  • This pattern simplifies the object creation process by placing it in a dedicated method, promoting loose coupling between the object creator and the objects themselves.
  • This approach enhances flexibility, extensibility, and maintainability, enabling subclasses to implement their own factory methods for creating specific object types.

Core Components of the Factory Method

Below are the main components of the Factory Design Pattern:

Class-Diagram
  • Creator: This is an abstract class or an interface that declares the factory method. The creator typically contains a method that serves as a factory for creating objects. It may also contain other methods that work with the created objects.
  • Concrete Creator: Concrete Creator classes are subclasses of the Creator that implement the factory method to create specific types of objects. Each Concrete Creator is responsible for creating a particular product.
  • Product: This is the interface or abstract class for the objects that the factory method creates. The Product defines the common interface for all objects that the factory method can create.
  • Concrete Product: Concrete Product classes are the actual objects that the factory method creates. Each Concrete Product class implements the Product interface or extends the Product abstract class.

Implementation of the Factory Method in C++

Let's implement the Factory Method Pattern in C++ step by step, explaining each part in detail. In this example, we'll create a simple shape factory that produces different shapes (e.g., Circle and Square).

Step 1: Define the Abstract Product (Shape)

C++
// Abstract product class class Shape { public:     virtual void draw() = 0;     virtual ~Shape() {} // Virtual destructor for polymorphism }; 

Here, we've defined an abstract class Shape with a pure virtual function draw(). This class represents the abstract product that all concrete products must inherit from.

Step 2: Define Concrete Products (Circle and Square)

C++
// Concrete product class - Circle class Circle : public Shape { public:     void draw() override {         std::cout<<"Drawing a Circle"<< std::endl;     } };  // Concrete product class - Square class Square : public Shape { public:     void draw() override {         std::cout<<"Drawing a Square"<<std::endl;     } }; 

Here, we have two concrete classes, Circle and Square, that inherits from the Shape abstract class. Each concrete product (Circle and Square) provides its implementation of the draw() method.

Step 3: Define the Abstract Creator

C++
// Abstract creator class class ShapeFactory { public:     virtual Shape* createShape() = 0;     virtual ~ShapeFactory() {} // Virtual destructor for polymorphism }; 

The abstract creator class, ShapeFactory, declare a pure virtual function createShape(), which will be implemented by concrete creators to create specific shapes.

Step 4: Define Concrete Creators (CircleFactory and Square Factory)

C++
// Concrete creator class - CircleFactory class CircleFactory : public ShapeFactory { public:     Shape* createShape() override {         return new Circle();     } };  // Concrete creator class - SquareFactory class SquareFactory : public ShapeFactory { public:     Shape* createShape() override {         return new Square();     } }; 

In this step, we've created two concrete creator classes, CircleFactory and SquareFactory, which implement the createShape() method to create instances of Circle and Square, respectively.

Step 5: Client Code

Now, let's create a client to use the Factory Method Pattern:

C++
int main() {     ShapeFactory* circleFactory = new CircleFactory();     ShapeFactory* squareFactory = new SquareFactory();      Shape* circle = circleFactory->createShape();     Shape* square = squareFactory->createShape();      circle->draw(); // Output: Drawing a Circle     square->draw(); // Output: Drawing a Square      delete circleFactory;     delete squareFactory;     delete circle;     delete square;      return 0; } 

In this client code, we first create instances of the concrete creators (circleFactory and squareFactory) and then use them to create instances of concrete products (cirlce and square). Finally, we call the draw() method on these objects, which produces the expected output.

Below is the complete combined code for the Factory Method Pattern in C++:

C++
// Abstract product class #include <bits/stdc++.h>; class Shape { public:     virtual void draw() = 0;     virtual ~Shape() {     } // Virtual destructor for polymorphism }; // Concrete product class - Circle class Circle : public Shape { public:     void draw() override     {         std::cout<<"Drawing a Circle"<<std::endl;     } };  // Concrete product class - Square class Square : public Shape { public:     void draw() override     {         std::cout<<"Drawing a Square"<<std::endl;     } }; // Abstract creator class class ShapeFactory { public:     virtual Shape* createShape() = 0;     virtual ~ShapeFactory() {     } // Virtual destructor for polymorphism }; // Concrete creator class - CircleFactory class CircleFactory : public ShapeFactory { public:     Shape* createShape() override { return new Circle(); } };  // Concrete creator class - SquareFactory class SquareFactory : public ShapeFactory { public:     Shape* createShape() override { return new Square(); } }; int main() {     ShapeFactory* circleFactory = new CircleFactory();     ShapeFactory* squareFactory = new SquareFactory();      Shape* circle = circleFactory->createShape();     Shape* square = squareFactory->createShape();      circle->draw(); // Output: Drawing a Circle     square->draw(); // Output: Drawing a Square      delete circleFactory;     delete squareFactory;     delete circle;     delete square;          // Client code based on user-input          /* cout << "Enter shape type (circle or square): ";     string shapeType;     cin >> shapeType;      ShapeFactory* shapeFactory = nullptr;     if (shapeType == "circle") {         shapeFactory = new CircleFactory();     } else if (shapeType == "square") {         shapeFactory = new SquareFactory();     } else {         cout << "Invalid shape type entered." << endl;         return 1;     }      Shape* shape = shapeFactory->createShape();     shape->draw();      delete shapeFactory;     delete shape; */      return 0; } 

Output
Drawing a Circle Drawing a Square

This implementation demonstrates the Factory Method Pattern, where:

  • The abstract creator (ShapeFactory) defines the factory method (createShape())
  • Concrete creators (CircleFactory and SquareFactory) implement this method to create concrete prodcuts (Circle and Square).
  • The client code interacts with the abstract creator, creating products without needing to know their specific types.
  • This promotes flexibility and decoupling between the client and product classes.

Use Cases of the Factory Method

Below are the main use cases of factory method design pattern:

  • Used in JDBC for creating connections and in frameworks like Spring for managing beans.
  • Libraries like Swing and JavaFX use factories to create flexible UI components.
  • Tools like Log4j rely on factories to create configurable loggers.
  • Factories help create objects from serialized data, supporting various formats.

Advantages of the Factory Method

Below are the main advantages of factory method design pattern:

  • Separates creation logic from client code, improving flexibility.
  • New product types can be added easily.
  • Simplifies unit testing by allowing mock product creation.
  • Centralizes object creation logic across the application.
  • Hides specific product classes from clients, reducing dependency.

Disadvantages of the Factory Method

Below are the main advantages of factory method design pattern:

  • Adds more classes and interfaces, which can complicate maintenance.
  • Slight performance impacts due to polymorphism.
  • Concrete creators are linked to their products.
  • Clients need knowledge of specific subclasses.
  • May lead to unnecessary complexity if applied too broadly.
  • Factory logic can be harder to test.

When to Use the Factory Method

Below is when to use factory method design pattern:

  • If your object creation process is complex or varies under different conditions, using a factory method can make your client code simpler and promote reusability.
  • The Factory Method Pattern allows you to create objects through an interface or abstract class, hiding the details of concrete implementations.
  • This reduces dependencies and makes it easier to modify or expand the system without affecting existing code.
  • If your application needs to create different versions of a product or may introduce new types in the future.
  • The Factory Method Pattern provides a flexible way to handle these variations by defining specific factory methods for each product type.

When Not to Use the Factory Method

Below is when to use factory method design pattern:

  • Avoid using the Factory Method pattern when your object creation process is straightforward and doesn’t require additional complexity.
  • Don’t implement it if you don’t need to hide concrete implementation details, as this can lead to unnecessary overhead.
  • Refrain from using the pattern if your application doesn’t anticipate creating different product versions or introducing new types in the future.
  • Skip the Factory Method if the added flexibility doesn’t provide significant benefits for your specific use case.

Conclusion

The Factory Method Pattern is a valuable tool in C++ for achieving flexible and extensible object creation mechanisms. By abstracting the creation process into separate factory methods, you can write more maintainable, modular and testable code. It is a fundamental patten to have in your arsenal when designing object-oriented systems, offering a solution to the often complex problem of object instantiation.


Next Article
Abstract Factory Pattern | C++ Design Patterns
author
thesunpandey
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023
  • C++ Design Pattern

Similar Reads

  • Modern C++ Design Patterns Tutorial
    Design patterns in C++ help developers create maintainable, flexible, and understandable code. They encapsulate the expertise and experience of seasoned software architects and developers, making it easier for newer programmers to follow established best practices. What are C++ Design Patterns?A des
    7 min read
  • Creational Software Design Patterns in C++

    • Factory Method Pattern | C++ Design Patterns
      Factory Method Pattern provides an interface for creating objects but leaves the actual object instantiation to derived classes. This allows for flexibility in object creation and promotes loose coupling between the client code and the concrete products. Table of Content What is the Factory Method D
      8 min read
    • Abstract Factory Pattern | C++ Design Patterns
      Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are
      6 min read
    • Builder Pattern | C++ Design Patterns
      The builder pattern is defined as a creational design pattern that separates the construction of a complex object from its representation, allowing us to create different representations of an object using the same construction process. It's beneficial when an object has many optional properties or
      6 min read
    • Prototype Pattern | C++ Design Patterns
      When designing software, it's crucial to make it efficient, easy to reuse, and simple to maintain. One way to achieve these goals is by using design patterns, and one such pattern is the Prototype Pattern. In this article, we'll explore the Prototype Design Pattern in the context of C++. Important T
      5 min read
    • Singleton Pattern | C++ Design Patterns
      A singleton pattern is a design pattern that ensures that only one instance of a class can exist in the entire program. This means that if you try to create another instance of the class, it will return the same instance that was created earlier. The Singleton pattern is useful when we need to have
      11 min read
    • Structural Software Design Patterns in C++

      • Adapter Pattern | C++ Design Patterns
        Adapter Pattern is a structural design pattern used to make two incompatible interfaces work together. It acts as a bridge between two incompatible interfaces, allowing them to collaborate without modifying their source code. This pattern is particularly useful when integrating legacy code or third-
        6 min read
      • Bridge Method | C++ Design Patterns
        Bridge Pattern is basically a structural design pattern in software engineering or in C++ programming that is used to separate an object's abstraction from its implementation. It is part of the Gang of Four (GoF) design patterns and is particularly useful when we need to avoid a permanent binding be
        9 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