Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Factory Pattern

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:

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"

)

   

   

print

(

dog.

speak

(

)

)

 

Output: Woof!

   

print

(

cat.

speak

(

)

)

 

Output: Meow!

   

print

(

duck.

speak

(

)

)

Output: Quack!

if

name

==

"main"

:

    test_simple_factory

(

)

Advantages and Disadvantages

Fixed size, stores elements of the same type.

High efficiency in random access of elements.

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

(

)

   

print

(

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

(

)

   

print

(

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

(

)

   

   

print

(

"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

)

:

       

print

(

f

"INFO: {message}"

)

   

   

def

error

(

self

,

message

)

:

       

print

(

f

"ERROR: {message}"

,

file

=

sys

.

stderr

)

   

   

def

debug

(

self

,

message

)

:

       

print

(

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:

Situations where it is not appropriate:

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

}

)

   

print

(

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:

Exercise 2: Extend the Database Factory

Based on the previous database factory example, add support for the PostgreSQL database.

Requirements:

Exercise 3: Configuration-Driven Factory

Create a system that can dynamically select a factory based on a configuration file.

Requirements:


Summary

The factory pattern is a very important creational pattern in Python design. By encapsulating the object creation process, it provides the following benefits:

  1. Reduced coupling: The client does not need to know the creation details of concrete products
  2. Improved maintainability: Creation logic is managed centrally, making it easy to modify and extend
  3. Enhanced flexibility: New product types can be easily added
  4. Promotes code reuse: Creation logic can be reused in multiple places

Remember to choose the appropriate factory pattern type:

By using the factory pattern appropriately, you can write more flexible, maintainable, and extensible Python code!