gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
What is a factory pattern in programming?
- User
What is a factory pattern in programming?
- Assistant
What is a factory pattern in programming?
The factory pattern is a design pattern used in object-oriented programming to create instances of a class. It provides a way to instantiate objects without specifying the exact class of object that will be created. This pattern is part of the creational group of patterns, which deal with object creation mechanisms.
Simple Factory:
Factory Method:
Abstract Factory:
Here's a simple illustration in Python:
from abc import ABC, abstractmethod
# Product interface
class Product(ABC):
@abstractmethod
def operation(self) -> str:
pass
# Concrete Products
class ConcreteProductA(Product):
def operation(self) -> str:
return "Result of ConcreteProductA"
class ConcreteProductB(Product):
def operation(self) -> str:
return "Result of ConcreteProductB"
# Creator class
class Creator(ABC):
@abstractmethod
def factory_method(self) -> Product:
pass
def some_operation(self) -> str:
product = self.factory_method()
return f"Creator: The same creator's code has just worked with {product.operation()}"
# Concrete Creators
class ConcreteCreatorA(Creator):
def factory_method(self) -> Product:
return ConcreteProductA()
class ConcreteCreatorB(Creator):
def factory_method(self) -> Product:
return ConcreteProductB()
# Client code
def client_code(creator: Creator) -> None:
print(f"Client: {creator.some_operation()}")
# Usage
client_code(ConcreteCreatorA())
client_code(ConcreteCreatorB())
In the example, ConcreteCreatorA and ConcreteCreatorB are responsible for creating instances of ConcreteProductA and ConcreteProductB, respectively, without the client needing to know which class to instantiate.
Not yet included in a published release.