Home >Backend Development >Python Tutorial >Strategy Design Pattern
The Strategy Design Pattern is a behavioral design pattern that enables selecting an algorithm's behavior at runtime.
Instead of implementing multiple variations of an algorithm in a single class, it allows you to define a family of algorithms, encapsulate each in its own class, and make them interchangeable.
Context Class: Maintains a reference to a Strategy object and interacts with it through a common interface.
Strategy Interface: Defines a common interface for all concrete strategies.
Concrete Strategies: Implement the Strategy interface with specific algorithms.
Use the Strategy Pattern when the benefits of flexibility and maintainability outweigh the overhead of managing multiple strategy classes.
Many Algorithms:
Runtime Decisions:
Avoid Excessive Use of if or switch Statements:
Encapsulation of Variations:
Open/Closed Principle:
from abc import ABC, abstractmethod from enum import Enum # Enum for User Types class UserType(Enum): FREE = 0 BASIC = 1 PREMIUM = 2 # Strategy Interface for Quality class Quality(ABC): @abstractmethod def get_quality(self): pass # Strategy Interface for Ad Policy class AdPolicy(ABC): @abstractmethod def has_ads(self): pass # Concrete Strategy for Quality class FreeUserQuality(Quality): def get_quality(self): return ['SD'] class BasicUserQuality(Quality): def get_quality(self): return ['SD', 'HD'] class PremiumUserQuality(Quality): def get_quality(self): return ['SD', 'HD', 'UHD'] # Concrete Strategy for Ad Policy class FreeUserAdPolicy(AdPolicy): def has_ads(self): return True class BasicUserAdPolicy(AdPolicy): def has_ads(self): return True class PremiumUserAdPolicy(AdPolicy): def has_ads(self): return False # Context Class class User: def __init__(self, user_type: UserType, quality: Quality, ad_policy: AdPolicy): self.user_type = user_type self.quality = quality self.ad_policy = ad_policy def get_quality(self): return self.quality.get_quality() def has_ads(self): return self.ad_policy.has_ads() # Usage free_user = User(UserType.FREE, FreeUserQuality(), FreeUserAdPolicy()) basic_user = User(UserType.BASIC, BasicUserQuality(), BasicUserAdPolicy()) premium_user = User(UserType.PREMIUM, PremiumUserQuality(), PremiumUserAdPolicy()) print("Free User Quality:", free_user.get_quality()) # ['SD'] print("Free User Ads:", free_user.has_ads()) # True print("Premium User Quality:", premium_user.get_quality()) # ['SD', 'HD', 'UHD'] print("Premium User Ads:", premium_user.has_ads()) # False
The above is the detailed content of Strategy Design Pattern. For more information, please follow other related articles on the PHP Chinese website!