策略设计模式是一种行为设计模式,它能够在运行时选择算法的行为。
不是在单个类中实现算法的多个变体,它允许您定义一系列算法,将每个算法封装在自己的类中,并使它们可以互换。
Context 类:维护对策略对象的引用并通过公共接口与其交互。
策略接口:为所有具体策略定义通用接口。
具体策略:使用特定算法实现策略接口。
当灵活性和可维护性的好处超过管理多个策略类的开销时,请使用策略模式。
多种算法:
运行时决策:
避免过多使用 if 或 switch 语句:
变体的封装:
开闭原则:
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
以上是策略设计模式的详细内容。更多信息请关注PHP中文网其他相关文章!