Strategy模式定义了一族可互换的算法/行为,将每个封装起来,使它们可在运行时相互替换。它让你动态选择算法并避免复杂的条件语句,促进灵活、可扩展的代码。
Strategy模式做什么
text
STRATEGY → encapsulate INTERCHANGEABLE algorithms/behaviors behind a common interface:
→ define a family of strategies (each implements the same interface)
→ the context uses a strategy via the interface → can SWAP strategies at runtime
→ choose the behavior dynamically without changing the context
→ "compose" behavior instead of hardcoding it (favor composition over conditionals)
示例
js
{ () { } }
{ () { } }
{
() { . = strategy; }
() { ..(amount); }
}
( ()).();
