02 Dec 2023
The Factory Design Pattern is a creational pattern that provides an interface for creating instances of a class, but allows subclasses to alter the type of instances that will be created. The main components of the Factory Design Pattern include:
-
Product:
- This is the interface or abstract class that defines the type of object the factory method creates. It declares the common interface for all concrete products.
public interface IProduct { void SomeMethod(); } -
Concrete Product:
- These are the classes that implement the
Productinterface. They represent the different types of objects that can be created by the factory.
public class ConcreteProductA : IProduct { public void SomeMethod() { // Implementation for ConcreteProductA } } public class ConcreteProductB : IProduct { public void SomeMethod() { // Implementation for ConcreteProductB } } - These are the classes that implement the
-
Factory:
- This is an interface or abstract class that declares the factory method for creating objects of the
Producttype.
public interface IFactory { IProduct CreateProduct(); } - This is an interface or abstract class that declares the factory method for creating objects of the
-
Concrete Factory:
- These are the classes that implement the
Factoryinterface and provide the implementation for the factory method. The concrete factory is responsible for creating an instance of a concrete product.
public class ConcreteFactoryA : IFactory { public IProduct CreateProduct() { return new ConcreteProductA(); } } public class ConcreteFactoryB : IFactory { public IProduct CreateProduct() { return new ConcreteProductB(); } } - These are the classes that implement the
client code: With this structure, the client code can use the factory to create instances of products without having to specify their concrete classes. This promotes flexibility and allows for easy extension when adding new products or changing existing ones.
// Client Code
class Program
{
static void Main()
{
// Client chooses a factory (ConcreteFactoryA)
IFactory factory = new ConcreteFactoryA();
// Client uses the factory to create a product (ConcreteProductA)
IProduct product = factory.CreateProduct();
// Client uses the product
product.SomeMethod(); // Output: ConcreteProductA's method called.
}
}
In summary, the Factory Design Pattern consists of a product interface, concrete product classes, a factory interface, and concrete factory classes that implement the factory method to create instances of products.