Python Factory Pattern
The Factory pattern is a creational design pattern that provides the best way to create objects.
Imagine ordering food at a restaurant: you do not need to know how the kitchen prepares the food; you just tell the waiter what you want, and the kitchen will make it for you.
The Factory pattern is just such a "kitchen": it is responsible for creating objects, and you only need to tell it what type of object you want.
Why do we need the Factory pattern?
In programming, we often need to create objects. If we directly use the new keyword or class constructor in code, it leads to:
- High code coupling: the code that creates objects is tightly bound to concrete classes
- Difficult to maintain: when you need to modify or add new object types, you have to modify code in many places
- Violates the Open-Closed Principle: the principle of being open for extension and closed for modification is broken
The Factory pattern solves these problems by encapsulating the object creation process.
Three Types of Factory Pattern
The factory pattern is mainly divided into three types. Let's understand them through concrete examples.
1. Simple Factory Pattern
The simple factory pattern is the most basic factory pattern. It creates different types of objects through a factory class.
Basic structure
Example
from
abc
import
ABC
,
abstractmethod
Product Interface
class
Animal
(
ABC
)
:
@
abstractmethod
def
speak
(
self
)
:
pass
Concrete product
class
Dog
(
Animal
)
:
def
speak
(
self
)
:
return
"Woof!"
class
Cat
(
Animal
)
:
def
speak
(
self
)
:
return
"Meow!"
class
Duck
(
Animal
)
:
def
speak
(
self
)
:
return
"Quack!"
Simple Factory
class
AnimalFactory:
@
staticmethod
def
create_animal
(
animal_type
)
:
if
animal_type
==
"dog"
:
return
Dog
(
)
elif
animal_type
==
"cat"
:
return
Cat
(
)
elif
animal_type
==
"duck"
:
return
Duck
(
)
else
:
raise
ValueError
(
f
"Unknown animal type: {animal_type}"
)
Usage examples
def
test_simple_factory
(
)
:
factory
=
AnimalFactory
(
)
dog
=
factory.
create_animal
(
"dog"
)
cat
=
factory.
create_animal
(
"cat"
)
duck
=
factory.
create_animal
(
"duck"
)
(
dog.
speak
(
)
)
Output: Woof!
(
cat.
speak
(
)
)
Output: Meow!
(
duck.
speak
(
)
)
Output: Quack!
if
name
==
"main"
:
test_simple_factory
(
)
Advantages and Disadvantages
Fixed size, stores elements of the same type.
- Decouples the client from concrete product classes
- Separation of responsibilities, easy to maintain
High efficiency in random access of elements.
- Adding a new product requires modifying the factory class, violating the open-closed principle
- The factory class has too many responsibilities, violating the single responsibility principle
2. Factory Method Pattern
The factory method pattern solves the problem of the simple factory pattern by letting subclasses decide what objects to create.
Basic structure
Example
from
abc
import
ABC
,
abstractmethod
Product Interface
class
Button
(
ABC
)
:
@
abstractmethod
def
render
(
self
)
:
pass
@
abstractmethod
def
onClick
(
self
)
:
pass
Concrete product
class
WindowsButton
(
Button
)
:
def
render
(
self
)
:
return
"Rendering a Windows-style button"
def
onClick
(
self
)
:
return
"Windows button was clicked"
class
MacButton
(
Button
)
:
def
render
(
self
)
:
return
"Rendering a Mac-style button"
def
onClick
(
self
)
:
return
"Mac button was clicked"
Creator Abstract Class
class
Dialog
(
ABC
)
:
@
abstractmethod
def
createButton
(
self
)
Button:
pass
def
render
(
self
)
:
Calling the factory method to create a product
button
=
self
.
createButton
(
)
result
=
button.
render
(
)
return
result
Concrete Creator
class
WindowsDialog
(
Dialog
)
:
def
createButton
(
self
)
Button:
return
WindowsButton
(
)
class
MacDialog
(
Dialog
)
:
def
createButton
(
self
)
Button:
return
MacButton
(
)
Usage examples
def
test_factory_method
(
)
:
Selecting a concrete factory based on configuration
config
=
"windows"
Can be read from a configuration file
if
config
==
"windows"
:
dialog
=
WindowsDialog
(
)
else
:
dialog
=
MacDialog
(
)
result
=
dialog.
render
(
)
(
result
)
if
name
==
"main"
:
test_factory_method
(
)
Factory Method Pattern Flow

3. Abstract Factory Pattern
The abstract factory pattern provides an interface for creating a family of related or dependent objects without specifying their concrete classes.
Basic structure
Example
from
abc
import
ABC
,
abstractmethod
Abstract Product A
class
Button
(
ABC
)
:
@
abstractmethod
def
paint
(
self
)
:
pass
Abstract Product B
class
Checkbox
(
ABC
)
:
@
abstractmethod
def
paint
(
self
)
:
pass
Concrete Product A1
class
WindowsButton
(
Button
)
:
def
paint
(
self
)
:
return
"Rendering a Windows button"
Concrete Product A2
class
MacButton
(
Button
)
:
def
paint
(
self
)
:
return
"Rendering a Mac button"
Concrete Product B1
class
WindowsCheckbox
(
Checkbox
)
:
def
paint
(
self
)
:
return
"Rendering a Windows checkbox"
Concrete Product B2
class
MacCheckbox
(
Checkbox
)
:
def
paint
(
self
)
:
return
"Rendering a Mac checkbox"
Abstract Factory
class
GUIFactory
(
ABC
)
:
@
abstractmethod
def
createButton
(
self
)
Button:
pass
@
abstractmethod
def
createCheckbox
(
self
)
Checkbox:
pass
Concrete Factory 1
class
WindowsFactory
(
GUIFactory
)
:
def
createButton
(
self
)
Button:
return
WindowsButton
(
)
def
createCheckbox
(
self
)
Checkbox:
return
WindowsCheckbox
(
)
Concrete Factory 2
class
MacFactory
(
GUIFactory
)
:
def
createButton
(
self
)
Button:
return
MacButton
(
)
def
createCheckbox
(
self
)
Checkbox:
return
MacCheckbox
(
)
Client code
class
Application:
def
init
(
self
,
factory: GUIFactory
)
:
self
.
factory
=
factory
self
.
button
=
None
self
.
checkbox
=
None
def
createUI
(
self
)
:
self
.
button
=
self
.
factory
.
createButton
(
)
self
.
checkbox
=
self
.
factory
.
createCheckbox
(
)
def
paint
(
self
)
:
result
=
[
]
if
self
.
button
:
result.
append
(
self
.
button
.
paint
(
)
)
if
self
.
checkbox
:
result.
append
(
self
.
checkbox
.
paint
(
)
)
return
"\n"
.
join
(
result
)
Usage examples
def
test_abstract_factory
(
)
:
Selecting a factory based on the system type
system_type
=
"windows"
Can be auto-detected or read from configuration
if
system_type
==
"windows"
:
factory
=
WindowsFactory
(
)
else
:
factory
=
MacFactory
(
)
app
=
Application
(
factory
)
app.
createUI
(
)
(
app.
paint
(
)
)
if
name
==
"main"
:
test_abstract_factory
(
)
Comparison of the Three Factory Patterns
| Feature | Simple Factory Pattern | Factory Method Pattern | Abstract Factory Pattern |
|---|---|---|---|
| Complexity | Low | Medium | High |
| Extensibility | Poor | Good | Very good |
| Applicable scenarios | Few object types | Single product family | Multiple related product families |
| Open-Closed Principle | Violates | Complies with | Complies with |
| Dependency Relationship | Depends on concrete classes | Depends on abstract classes | Depends on abstract interfaces |
Practical Application Scenarios
Scenario 1: Database Connection Factory
Example
from
abc
import
ABC
,
abstractmethod
import
sqlite3
import
mysql.
connector
Database Connection Interface
class
DatabaseConnection
(
ABC
)
:
@
abstractmethod
def
connect
(
self
)
:
pass
@
abstractmethod
def
execute
(
self
,
query
)
:
pass
Concrete Database Connection
class
SQLiteConnection
(
DatabaseConnection
)
:
def
init
(
self
,
db_path
)
:
self
.
db_path
=
db_path
self
.
connection
=
None
def
connect
(
self
)
:
self
.
connection
=
sqlite3.
connect
(
self
.
db_path
)
return
self
.
connection
def
execute
(
self
,
query
)
:
if
self
.
connection
:
cursor
=
self
.
connection
.
cursor
(
)
cursor.
execute
(
query
)
return
cursor.
fetchall
(
)
class
MySQLConnection
(
DatabaseConnection
)
:
def
init
(
self
,
host
,
user
,
password
,
database
)
:
self
.
host
=
host
self
.
user
=
user
self
.
password
=
password
self
.
database
=
database
self
.
connection
=
None
def
connect
(
self
)
:
self
.
connection
=
mysql.
connector
.
connect
(
host
=
self
.
host
,
user
=
self
.
user
,
password
=
self
.
password
,
database
=
self
.
database
)
return
self
.
connection
def
execute
(
self
,
query
)
:
if
self
.
connection
:
cursor
=
self
.
connection
.
cursor
(
)
cursor.
execute
(
query
)
return
cursor.
fetchall
(
)
Database Factory
class
DatabaseFactory:
@
staticmethod
def
create_connection
(
db_type
,
**kwargs
)
:
if
db_type
==
"sqlite"
:
return
SQLiteConnection
(
**kwargs
)
elif
db_type
==
"mysql"
:
return
MySQLConnection
(
**kwargs
)
else
:
raise
ValueError
(
f
"Unsupported database type: {db_type}"
)
Usage examples
def
test_database_factory
(
)
:
Creating a SQLite connection
sqlite_conn
=
DatabaseFactory.
create_connection
(
"sqlite"
,
db_path
=
"example.db"
)
sqlite_conn.
connect
(
)
Creating a MySQL connection
mysql_conn
=
DatabaseFactory.
create_connection
(
"mysql"
,
host
=
"localhost"
,
user
=
"root"
,
password
=
"password"
,
database
=
"test"
)
mysql_conn.
connect
(
)
(
"Database connection created successfully!"
)
if
name
==
"main"
:
test_database_factory
(
)
Scenario 2: Logger Factory
Example
import
logging
from
abc
import
ABC
,
abstractmethod
import
sys
Logger Interface
class
Logger
(
ABC
)
:
@
abstractmethod
def
info
(
self
,
message
)
:
pass
@
abstractmethod
def
error
(
self
,
message
)
:
pass
@
abstractmethod
def
debug
(
self
,
message
)
:
pass
Console Logger
class
ConsoleLogger
(
Logger
)
:
def
info
(
self
,
message
)
:
(
f
"INFO: {message}"
)
def
error
(
self
,
message
)
:
(
f
"ERROR: {message}"
,
file
=
sys
.
stderr
)
def
debug
(
self
,
message
)
:
(
f
"DEBUG: {message}"
)
File Logger
class
FileLogger
(
Logger
)
:
def
init
(
self
,
filename
)
:
self
.
filename
=
filename
def
info
(
self
,
message
)
:
with
open
(
self
.
filename
,
'a'
)
as
f:
f.
write
(
f
"INFO: {message}\n"
)
def
error
(
self
,
message
)
:
with
open
(
self
.
filename
,
'a'
)
as
f:
f.
write
(
f
"ERROR: {message}\n"
)
def
debug
(
self
,
message
)
:
with
open
(
self
.
filename
,
'a'
)
as
f:
f.
write
(
f
"DEBUG: {message}\n"
)
Logger Factory
class
LoggerFactory:
@
staticmethod
def
get_logger
(
logger_type
,
**kwargs
)
:
if
logger_type
==
"console"
:
return
ConsoleLogger
(
)
elif
logger_type
==
"file"
:
return
FileLogger
(
**kwargs
)
else
:
raise
ValueError
(
f
"Unsupported logger type: {logger_type}"
)
Usage examples
def
test_logger_factory
(
)
:
Creating a console logger
console_logger
=
LoggerFactory.
get_logger
(
"console"
)
console_logger.
info
(
"This is an information message"
)
console_logger.
error
(
"This is an error message"
)
Creating a file logger
file_logger
=
LoggerFactory.
get_logger
(
"file"
,
filename
=
"app.log"
)
file_logger.
info
(
"Information logged to file"
)
file_logger.
debug
(
"Debug information"
)
if
name
==
"main"
:
test_logger_factory
(
)
Best practices and notes
1. When to Use the Factory Pattern?
Situations where the factory pattern is appropriate:
- The object creation process is complex
- Different objects need to be created based on different conditions
- You want to separate object creation from usage
- The system needs to support multiple types of products
Situations where it is not appropriate:
- Object creation is simple; using the constructor directly is sufficient
- There are few product types and they are unlikely to expand
2. Common Mistakes and How to Avoid Them
Mistake 1: Over-engineering
Example
Not recommended: Using a complex factory for simple cases
class
SimpleObject:
def
init
(
self
,
name
)
:
self
.
name
=
name
An over-engineered factory
class
SimpleObjectFactory:
@
staticmethod
def
create_simple_object
(
name
)
:
return
SimpleObject
(
name
)
Recommended: Direct creation
obj
=
SimpleObject
(
"test"
)
Mistake 2: Factory Class with Too Many Responsibilities
Example
Not recommended: One factory doing too many things
class
GodFactory:
def
create_user
(
self
)
: ...
def
create_order
(
self
)
: ...
def
create_product
(
self
)
: ...
def
send_email
(
self
)
: ...
This is not creating an object!
Recommended: Separate by responsibility
class
UserFactory: ...
class
OrderFactory: ...
class
ProductFactory: ...
3. Combining with Dependency Injection
The factory pattern is often used together with dependency injection (DI):
Example
from
abc
import
ABC
,
abstractmethod
Service Interface
class
NotificationService
(
ABC
)
:
@
abstractmethod
def
send
(
self
,
message
)
:
pass
Concrete Service
class
EmailService
(
NotificationService
)
:
def
send
(
self
,
message
)
:
return
f
"Sending email: {message}"
class
SMSService
(
NotificationService
)
:
def
send
(
self
,
message
)
:
return
f
"Sending SMS: {message}"
Factory
class
NotificationFactory:
@
staticmethod
def
create_service
(
service_type
)
:
if
service_type
==
"email"
:
return
EmailService
(
)
elif
service_type
==
"sms"
:
return
SMSService
(
)
else
:
raise
ValueError
(
f
"Unknown service type: {service_type}"
)
Class Using Dependency Injection
class
OrderProcessor:
def
init
(
self
,
notification_service: NotificationService
)
:
self
.
notification_service
=
notification_service
def
process_order
(
self
,
order
)
:
Handling order logic
result
=
self
.
notification_service
.
send
(
"Order processing complete"
)
return
result
Use
def
main
(
)
:
Creating a service through the factory
notification_service
=
NotificationFactory.
create_service
(
"email"
)
Injecting dependencies
processor
=
OrderProcessor
(
notification_service
)
result
=
processor.
process_order
(
{
"id"
:
1
}
)
(
result
)
if
name
==
"main"
:
main
(
)
Exercises
Exercise 1: Implement a Shape Factory
Create a shape factory that supports circles (Circle), rectangles (Rectangle), and triangles (Triangle). Each shape should have methods to calculate its area and perimeter.
Requirements:
- Use the factory method pattern
- Implement each shape class
calculate_area()andcalculate_perimeter()Method - Provide usage examples
Exercise 2: Extend the Database Factory
Based on the previous database factory example, add support for the PostgreSQL database.
Requirements:
- creation
PostgreSQLConnectionclass - Modify the factory to support the new database type
- Ensure existing code is not broken
Exercise 3: Configuration-Driven Factory
Create a system that can dynamically select a factory based on a configuration file.
Requirements:
- Read configuration from a JSON or YAML file
- Create the corresponding object based on the configuration
- Support hot-reloading of configuration
Summary
The factory pattern is a very important creational pattern in Python design. By encapsulating the object creation process, it provides the following benefits:
- Reduced coupling: The client does not need to know the creation details of concrete products
- Improved maintainability: Creation logic is managed centrally, making it easy to modify and extend
- Enhanced flexibility: New product types can be easily added
- Promotes code reuse: Creation logic can be reused in multiple places
Remember to choose the appropriate factory pattern type:
- Simple Factory: Suitable for scenarios with few product types that do not change much
- Factory Method: Suitable for scenarios that need to extend the product family
- Abstract Factory: Suitable for complex scenarios that need to create families of related products
By using the factory pattern appropriately, you can write more flexible, maintainable, and extensible Python code!