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

Python Strategy Pattern

Python Strategy Pattern

The Strategy Pattern is a behavioral design pattern that lets you select an algorithm or behavior at runtime. Simply put, it encapsulates different algorithms into separate classes so they can be interchanged.

Core idea

Imagine ordering food at a restaurant: you can choose different payment methods - cash, credit card, mobile payment, etc. No matter which method you choose, you can complete the payment; only the specific process differs. This is a real-life example of the Strategy Pattern.

Design Principles

The Strategy pattern follows these important principles:


Structure of the Strategy Pattern

Let's understand the composition of the Strategy pattern through a UML class diagram:

Component Description

Context

Strategy (strategy interface)

ConcreteStrategy (concrete strategy)


Basic Syntax and Implementation

Strategy Interface Definition

In Python, we can use an abstract base class (ABC) to define the strategy interface:

Example

from

abc

import

ABC

,

abstractmethod

class

PaymentStrategy

(

ABC

)

:

   

"""Abstract base class for payment strategies"""

   

   

@

abstractmethod

   

def

pay

(

self

,

amount:

float

)

bool

:

       

"""Payment method"""

       

pass

Concrete Strategy Implementation

Example

class

CreditCardPayment

(

PaymentStrategy

)

:

   

"""Credit card payment strategy"""

   

   

def

init

(

self

,

card_number:

str

,

expiry_date:

str

,

cvv:

str

)

:

       

self

.

card_number

=

card_number

       

self

.

expiry_date

=

expiry_date

       

self

.

cvv

=

cvv

   

   

def

pay

(

self

,

amount:

float

)

bool

:

       

print

(

f

"Pay {amount} yuan by credit card"

)

       

print

(

f

"Card number: {self.card_number}"

)

       

Actual payment logic should go here

       

return

True

class

AlipayPayment

(

PaymentStrategy

)

:

   

"""Alipay payment strategy"""

   

   

def

init

(

self

,

account:

str

)

:

       

self

.

account

=

account

   

   

def

pay

(

self

,

amount:

float

)

bool

:

       

print

(

f

"Pay {amount} yuan via Alipay"

)

       

print

(

f

"Alipay account: {self.account}"

)

       

Actual payment logic should go here

       

return

True

class

WechatPayment

(

PaymentStrategy

)

:

   

"""WeChat Pay strategy"""

   

   

def

init

(

self

,

openid:

str

)

:

       

self

.

openid

=

openid

   

   

def

pay

(

self

,

amount:

float

)

bool

:

       

print

(

f

"Pay {amount} yuan via WeChat Pay"

)

       

print

(

f

"WeChat OpenID: {self.openid}"

)

       

Actual payment logic should go here

       

return

True

Context Class Implementation

Example

class

PaymentContext:

   

"""Payment context class"""

   

   

def

init

(

self

,

strategy: PaymentStrategy

=

None

)

:

       

self

._strategy

=

strategy

   

   

def

set_strategy

(

self

,

strategy: PaymentStrategy

)

:

       

"""Set the payment strategy"""

       

self

._strategy

=

strategy

   

   

def

execute_payment

(

self

,

amount:

float

)

bool

:

       

"""Execute the payment"""

       

if

not

self

._strategy:

           

raise

ValueError

(

"No payment strategy set"

)

       

       

return

self

._strategy.

pay

(

amount

)


Complete Example: E-commerce Payment System

Let's demonstrate the practical application of the Strategy pattern through a complete e-commerce payment system:

Example

from

abc

import

ABC

,

abstractmethod

from

typing

import

Dict

,

Any

Strategy Interface

class

DiscountStrategy

(

ABC

)

:

   

"""Discount strategy interface"""

   

   

@

abstractmethod

   

def

calculate_discount

(

self

,

original_price:

float

)

float

:

       

"""Calculate the discounted price"""

       

pass

Concrete Strategy Implementation

class

NoDiscountStrategy

(

DiscountStrategy

)

:

   

"""No discount strategy"""

   

   

def

calculate_discount

(

self

,

original_price:

float

)

float

:

       

return

original_price

class

PercentageDiscountStrategy

(

DiscountStrategy

)

:

   

"""Percentage discount strategy"""

   

   

def

init

(

self

,

percentage:

float

)

:

       

if

not

0

<=

percentage

<=

100

:

           

raise

ValueError

(

"Discount percentage must be between 0 and 100"

)

       

self

.

percentage

=

percentage

   

   

def

calculate_discount

(

self

,

original_price:

float

)

float

:

        discount_amount

=

original_price *

(

self

.

percentage

/

100

)

       

return

original_price - discount_amount

class

FixedAmountDiscountStrategy

(

DiscountStrategy

)

:

   

"""Fixed amount discount strategy"""

   

   

def

init

(

self

,

discount_amount:

float

)

:

       

if

discount_amount

<

0

:

           

raise

ValueError

(

"Discount amount cannot be negative"

)

       

self

.

discount_amount

=

discount_amount

   

   

def

calculate_discount

(

self

,

original_price:

float

)

float

:

       

return

max

(

0

,

original_price -

self

.

discount_amount

)

class

SeasonalDiscountStrategy

(

DiscountStrategy

)

:

   

"""Seasonal discount strategy"""

   

   

def

init

(

self

,

base_discount:

float

,

seasonal_multiplier:

float

)

:

       

self

.

base_discount

=

base_discount

       

self

.

seasonal_multiplier

=

seasonal_multiplier

   

   

def

calculate_discount

(

self

,

original_price:

float

)

float

:

        total_discount

=

self

.

base_discount

self

.

seasonal_multiplier

       

return

max

(

0

,

original_price - total_discount

)

Context Class

class

ShoppingCart:

   

"""Shopping cart class"""

   

   

def

init

(

self

)

:

       

self

.

items

=

[

]

       

self

._discount_strategy

=

NoDiscountStrategy

(

)

   

   

def

add_item

(

self

,

item:

str

,

price:

float

)

:

       

"""Add an item"""

       

self

.

items

.

append

(

{

"item"

: item

,

"price"

: price

}

)

   

   

def

set_discount_strategy

(

self

,

strategy: DiscountStrategy

)

:

       

"""Set the discount strategy"""

       

self

._discount_strategy

=

strategy

   

   

def

calculate_total

(

self

)

float

:

       

"""Calculate the total price"""

        total

=

sum

(

item

[

"price"

]

for

item

in

self

.

items

)

       

return

self

._discount_strategy.

calculate_discount

(

total

)

   

   

def

display_cart

(

self

)

:

       

"""Display the cart contents"""

       

print

(

"Cart contents:"

)

       

for

item

in

self

.

items

:

           

print

(

f

" - {item['item']}: {item['price']} yuan"

)

       

        original_total

=

sum

(

item

[

"price"

]

for

item

in

self

.

items

)

        final_total

=

self

.

calculate_total

(

)

       

       

print

(

f

"Original price: {original_total} yuan"

)

       

print

(

f

"Discounted price: {final_total} yuan"

)

       

       

if

original_total

!=

final_total:

            discount

=

original_total - final_total

           

print

(

f

"Saved: {discount} yuan"

)

Usage examples

def

main

(

)

:

   

Create a shopping cart

    cart

=

ShoppingCart

(

)

   

   

Add items

    cart.

add_item

(

"Python programming book"

,

89.0

)

    cart.

add_item

(

"Wireless mouse"

,

129.0

)

    cart.

add_item

(

"Mechanical keyboard"

,

399.0

)

   

   

print

(

"=== No discount ==="

)

    cart.

set_discount_strategy

(

NoDiscountStrategy

(

)

)

    cart.

display_cart

(

)

   

   

print

(

"\n=== 20% off ==="

)

    cart.

set_discount_strategy

(

PercentageDiscountStrategy

(

20

)

)

 

20% off

    cart.

display_cart

(

)

   

   

print

(

"\n=== Full-reduction discount (minus 50 yuan) ==="

)

    cart.

set_discount_strategy

(

FixedAmountDiscountStrategy

(

50

)

)

    cart.

display_cart

(

)

   

   

print

(

"\n=== Seasonal discount ==="

)

    cart.

set_discount_strategy

(

SeasonalDiscountStrategy

(

30

,

1.5

)

)

 

Base discount 30, seasonal factor 1.5

    cart.

display_cart

(

)

if

name

==

"main"

:

    main

(

)

Run the above code and you will see the following output:

=== 无折扣 ===
Shopping cart contents:
  - Python编程书: 89.0元
  - 无线鼠标: 129.0元
  - 机械键盘: 399.0元
原价: 617.0元
折后价: 617.0元

=== 8折优惠 ===
Shopping cart contents:
  - Python编程书: 89.0元
  - 无线鼠标: 129.0元
  - 机械键盘: 399.0元
原价: 617.0元
折后价: 493.6元
节省: 123.4元

=== 满减优惠(减50元)===
Shopping cart contents:
  - Python编程书: 89.0元
  - 无线鼠标: 129.0元
  - 机械键盘: 399.0元
原价: 617.0元
折后价: 567.0元
节省: 50.0元

=== 季节性优惠 ===
Shopping cart contents:
  - Python编程书: 89.0元
  - 无线鼠标: 129.0元
  - 机械键盘: 399.0元
原价: 617.0元
折后价: 572.0元
节省: 45.0元

Advanced Usage of the Strategy Pattern

1. Strategy Factory Pattern

Combine the Factory pattern to manage strategy creation:

Example

class

DiscountStrategyFactory:

   

"""Discount strategy factory"""

   

   

@

staticmethod

   

def

create_strategy

(

strategy_type:

str

,

**kwargs

)

DiscountStrategy:

       

"""Create a discount strategy"""

        strategies

=

{

           

"no_discount"

: NoDiscountStrategy

,

           

"percentage"

: PercentageDiscountStrategy

,

           

"fixed_amount"

: FixedAmountDiscountStrategy

,

           

"seasonal"

: SeasonalDiscountStrategy

       

}

       

       

if

strategy_type

not

in

strategies:

           

raise

ValueError

(

f

"Unsupported strategy type: {strategy_type}"

)

       

       

return

strategies

[

strategy_type

]

(

**kwargs

)

Use the factory pattern

factory

=

DiscountStrategyFactory

(

)

Create different strategies

strategy1

=

factory.

create_strategy

(

"percentage"

,

percentage

=

15

)

 

15% off

strategy2

=

factory.

create_strategy

(

"fixed_amount"

,

discount_amount

=

100

)

 

Minus 100 yuan

2. Dynamic Strategy Selection

Dynamically select a strategy based on conditions:

Example

class

DynamicDiscountSelector:

   

"""Dynamic discount selector"""

   

   

@

staticmethod

   

def

select_strategy

(

user_type:

str

,

total_amount:

float

)

DiscountStrategy:

       

"""Select a strategy based on user type and total amount"""

       

if

user_type

==

"vip"

:

           

if

total_amount

500

:

               

return

PercentageDiscountStrategy

(

25

)

 

VIP: 25% off on orders over 500

           

else

:

               

return

PercentageDiscountStrategy

(

15

)

 

VIP: 15% off

       

elif

user_type

==

"normal"

:

           

if

total_amount

300

:

               

return

FixedAmountDiscountStrategy

(

30

)

 

Regular users: minus 30 on orders over 300

           

else

:

               

return

NoDiscountStrategy

(

)

       

else

:

           

return

NoDiscountStrategy

(

)

Use dynamic selection

cart

=

ShoppingCart

(

)

cart.

add_item

(

"Item A"

,

200

)

cart.

add_item

(

"Item B"

,

150

)

selector

=

DynamicDiscountSelector

(

)

strategy

=

selector.

select_strategy

(

"vip"

,

cart.

calculate_total

(

)

)

cart.

set_discount_strategy

(

strategy

)

cart.

display_cart

(

)


Advantages and Applicable Scenarios of the Strategy Pattern

Advantage comparison

Feature Traditional Approach Strategy Pattern
Extensibility Need to modify existing code Just add a new strategy class
Maintainability High code coupling Separation of responsibilities, easy to maintain
Flexibility Hard to switch algorithms at runtime Strategies can be switched dynamically
Testability Hard to test algorithms individually Each strategy can be tested independently

Applicable scenarios

  1. Multiple algorithm variants: When you have multiple similar classes that differ only in certain behaviors
  2. Avoid conditional statements: When you want to avoid using large numbers of conditional statements (if-else or switch)
  3. Runtime algorithm selection: When you need to choose different algorithms at runtime
  4. Algorithm encapsulation: When you want to isolate algorithm details from the client that uses them

Inapplicable Scenarios

  1. Simple algorithms: If there are only one or two algorithms that rarely change, it may be over-engineering
  2. The client needs to understand strategy details: If the client must know the concrete implementation of the strategies
  3. Too many strategies: When the number of strategy classes explodes, consider other patterns

Best practices and notes

Code Organization Recommendations

Example

Recommended file structure

project/

├── strategies/

│   ├──

init

.

py

│   ├── base_strategy.

py

     

Base strategy interface

│   ├── discount_strategies.

py

Discount-related strategies

│   └── payment_strategies.

py

Payment-related strategies

├── contexts/

│   ├──

init

.

py

│   └── shopping_cart.

py

     

Context Class

└── main.

py

Error handling

Example

class

SafeDiscountStrategy

(

DiscountStrategy

)

:

   

"""Discount strategy with error handling"""

   

   

def

init

(

self

,

base_strategy: DiscountStrategy

,

fallback_strategy: DiscountStrategy

=

None

)

:

       

self

.

base_strategy

=

base_strategy

       

self

.

fallback_strategy

=

fallback_strategy

or

NoDiscountStrategy

(

)

   

   

def

calculate_discount

(

self

,

original_price:

float

)

float

:

       

try

:

           

return

self

.

base_strategy

.

calculate_discount

(

original_price

)

       

except

Exception

as

e:

           

print

(

f

"Discount calculation error: {e}, using fallback strategy"

)

           

return

self

.

fallback_strategy

.

calculate_discount

(

original_price

)

Performance considerations

For performance-sensitive scenarios, consider the following optimizations:

Example

from

functools

import

lru_cache

class

CachedDiscountStrategy

(

DiscountStrategy

)

:

   

"""Discount strategy with caching"""

   

   

def

init

(

self

,

base_strategy: DiscountStrategy

)

:

       

self

.

base_strategy

=

base_strategy

   

   

@

lru_cache

(

maxsize

=

128

)

   

def

calculate_discount

(

self

,

original_price:

float

)

float

:

       

return

self

.

base_strategy

.

calculate_discount

(

original_price

)


Practical Exercise

Exercise 1: Sorting Strategy Implementation

Implement a sorter that supports multiple sorting algorithms:

Example

from

abc

import

ABC

,

abstractmethod

from

typing

import

List

class

SortStrategy

(

ABC

)

:

   

@

abstractmethod

   

def

sort

(

self

,

data: List

)

List:

       

pass

to-do: Implement a bubble sort strategy

class

BubbleSortStrategy

(

SortStrategy

)

:

   

def

sort

(

self

,

data: List

)

List:

       

Your implementation code

       

pass

to-do: Implement a quick sort strategy  

class

QuickSortStrategy

(

SortStrategy

)

:

   

def

sort

(

self

,

data: List

)

List:

       

Your implementation code

       

pass

to-do: Implement a merge sort strategy

class

MergeSortStrategy

(

SortStrategy

)

:

   

def

sort

(

self

,

data: List

)

List:

       

Your implementation code

       

pass

class

Sorter:

   

def

init

(

self

,

strategy: SortStrategy

=

None

)

:

       

self

._strategy

=

strategy

   

   

def

set_strategy

(

self

,

strategy: SortStrategy

)

:

       

self

._strategy

=

strategy

   

   

def

sort_data

(

self

,

data: List

)

List:

       

if

not

self

._strategy:

           

raise

ValueError

(

"No sorting strategy set"

)

       

return

self

._strategy.

sort

(

data

)

Test your implementation

data

=

[

64

,

34

,

25

,

12

,

22

,

11

,

90

]

sorter

=

Sorter

(

BubbleSortStrategy

(

)

)

result

=

sorter.

sort_data

(

data

)

print

(

f

"Sort result: {result}"

)

Exercise 2: File Compression Strategy

Design a file compressor that supports multiple compression formats:

Example

from

abc

import

ABC

,

abstractmethod

class

CompressionStrategy

(

ABC

)

:

   

@

abstractmethod

   

def

compress

(

self

,

file_path:

str

)

str

:

       

pass

   

   

@

abstractmethod

   

def

decompress

(

self

,

file_path:

str

)

str

:

       

pass

to-do: Implement a ZIP compression strategy

class

ZipCompressionStrategy

(

CompressionStrategy

)

:

   

def

compress

(

self

,

file_path:

str

)

str

:

       

Your implementation code

       

pass

   

   

def

decompress

(

self

,

file_path:

str

)

str

:

       

Your implementation code

       

pass

to-do: Implement a GZIP compression strategy

class

GzipCompressionStrategy

(

CompressionStrategy

)

:

   

def

compress

(

self

,

file_path:

str

)

str

:

       

Your implementation code

       

pass

   

   

def

decompress

(

self

,

file_path:

str

)

str

:

       

Your implementation code

       

pass

class

FileCompressor:

   

def

init

(

self

,

strategy: CompressionStrategy

=

None

)

:

       

self

._strategy

=

strategy

   

   

def

set_strategy

(

self

,

strategy: CompressionStrategy

)

:

       

self

._strategy

=

strategy

   

   

def

compress_file

(

self

,

file_path:

str

)

str

:

       

if

not

self

._strategy:

           

raise

ValueError

(

"No compression strategy set"

)

       

return

self

._strategy.

compress

(

file_path

)

   

   

def

decompress_file

(

self

,

file_path:

str

)

str

:

       

if

not

self

._strategy:

           

raise

ValueError

(

"No compression strategy set"

)

       

return

self

._strategy.

decompress

(

file_path

)


Summary

The Strategy pattern is a very practical design pattern in Python. By encapsulating algorithms into independent strategy classes, it provides good extensibility and flexibility. Through this article, you should be able to:

  1. Understand the core concepts and applicable scenarios of the Strategy pattern
  2. Master the basic implementation methods of the Strategy pattern
  3. Apply the Strategy pattern appropriately in real projects
  4. Avoid common misuses of the Strategy pattern