Skip to content

techtrendings.com

Let's explore

Menu
Menu

C++ – Factory Design Pattern – Creation Design Pattern

Posted on January 18, 2023January 18, 2023 by Avidlearner

The Factory design pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

Here’s an example of how the Factory pattern might be implemented in C++:

class Product {
 public:
  virtual ~Product() {}
};

class ConcreteProductA : public Product {
 public:
  // Implementation for ConcreteProductA
};

class ConcreteProductB : public Product {
 public:
  // Implementation for ConcreteProductB
};

class Factory {
 public:
  virtual Product* create_product() = 0;
};

class ConcreteFactoryA : public Factory {
 public:
  Product* create_product() {
    return new ConcreteProductA;
  }
};

class ConcreteFactoryB : public Factory {
 public:
  Product* create_product() {
    return new ConcreteProductB;
  }
};

In this example, the Product class is an interface that defines the interface of the objects that the factory will create. The ConcreteProductA and ConcreteProductB classes are concrete implementations of the Product class. The Factory class is an interface that defines a method for creating products. The ConcreteFactoryA and ConcreteFactoryB classes are concrete implementations of the Factory class, each with its own implementation of the create_product method, which creates instances of ConcreteProductA and ConcreteProductB respectively.

This allows the client code to use the factory to create objects, without having to know the specific type of object that will be created. This makes the code more flexible, since new types of objects can be added without having to modify the client code.

Related

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Implement Trie Data Structure in C++- LeetCode
  • How TLS Works
  • C++ – Factory Design Pattern – Creation Design Pattern
  • C++ – Strategy Design Pattern – Behavioral Design Pattern
  • LFU Cache Implementation – LeetCode

Recent Comments

  • automatically like friends photos on instagram on Program to find unpaired element in an Array in C++|Leetcode |techtrendings
  • Twicsy on Program to find unpaired element in an Array in C++|Leetcode |techtrendings

Archives

  • January 2023
  • November 2022
  • August 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022

Categories

  • Algorithm
  • Algorithm
  • C++
  • Design Patterns
  • Multithreading
  • OS Concepts
  • Programming
  • Uncategorized

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Join Our Mailing List for the Latest News and Updates.

© 2023 techtrendings.com | Powered by Superbs Personal Blog theme