Loading...
Loading...
Compare original and translation side by side
if method == "card": ... elif method == "paypal": ...if method == "card": ... elif method == "paypal": ...| Role | Responsibility |
|---|---|
| Context | Holds a reference to one strategy; delegates the varying work to it; exposes a setter (or constructor) so clients can inject/replace the strategy. |
| Strategy (protocol/ABC) | Common contract for all strategies (e.g. single method like |
| Concrete strategies | Implement the protocol/ABC; each encapsulates one variant of the algorithm. |
| Client | Chooses a concrete strategy and passes it to the context (e.g. from request params, config, or factory). |
| 角色 | 职责 |
|---|---|
| 上下文(Context) | 持有一个策略的引用;将可变工作委托给策略;暴露setter方法(或构造函数),以便客户端注入/替换策略。 |
| 策略(Strategy,protocol/ABC) | 所有策略的通用契约(例如单个方法 |
| 具体策略(Concrete strategies) | 实现protocol/ABC;每个策略封装算法的一种变体。 |
| 客户端(Client) | 选择具体策略并将其传递给上下文(例如从请求参数、配置或工厂中获取)。 |
undefinedundefineddef _stripe_charge(self, amount: float, details: dict) -> dict: ...
def _paypal_charge(self, amount: float, details: dict) -> dict: ...
def _bank_transfer(self, amount: float, details: dict) -> dict: ...
Problems: context grows with every variant; touching one method risks breaking others; hard to test in isolation; violates Open/Closed.def _stripe_charge(self, amount: float, details: dict) -> dict: ...
def _paypal_charge(self, amount: float, details: dict) -> dict: ...
def _bank_transfer(self, amount: float, details: dict) -> dict: ...
问题:上下文会随每个变体不断膨胀;修改一个方法可能影响其他方法;难以独立测试;违反开闭原则。undefinedundefined
**Concrete strategies** (one variant per class):
```python
**具体策略(每个变体对应一个类):**
```python
**Context** (depends only on the protocol):
```python
**上下文(仅依赖于protocol):**
```pythondef set_strategy(self, strategy: PaymentStrategy) -> None:
self._strategy = strategy
def process_payment(self, amount: float, details: dict) -> dict:
return self._strategy.execute(amount, details)
**Client** (e.g. FastAPI route) selects strategy and calls context:
```pythondef set_strategy(self, strategy: PaymentStrategy) -> None:
self._strategy = strategy
def process_payment(self, amount: float, details: dict) -> dict:
return self._strategy.execute(amount, details)
**客户端(例如FastAPI路由)选择策略并调用上下文:**
```python
Benefits: add new payment methods by adding a new strategy class and registering it; context and other strategies stay unchanged; each strategy is easy to unit test.
---
优势:新增支付方式只需添加新的策略类并注册;上下文和其他策略无需修改;每个策略易于进行单元测试。
---typing.Protocolabc.ABCasync def execute(...)AsyncPaymentStrategystrategies/stripe_strategy.pystrategies/base.pystrategies/payment_strategy.pytyping.Protocolabc.ABCasync def execute(...)AsyncPaymentStrategystrategies/stripe_strategy.pystrategies/base.pystrategies/payment_strategy.py