策略設計模式是一種行為設計模式,它能夠在運行時選擇演算法的行為。
不是在單一類別中實現演算法的多個變體,它允許您定義一系列演算法,將每個演算法封裝在自己的類別中,並使它們可以互換。
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中文網其他相關文章!