State: Problem
A finite number of states
The program behaves differently within a state
Can be switched from one state to another, and switching rules (transitions) are also finite and predetermined
有限数量的状态
程序在某个状态下的行为有所不同
可以从一种状态切换到另一种状态,并且切换规则(转换)也是有限且预先确定的
State: Solution
Create new classes for all possible states, and extract all state-specific behaviors into these classes
为所有可能的状态创建新类,并将所有特定于状态的行为提取到这些类中
Strategy: Problem
Example: route planning feature in a navigation app
V1: routes over roads
V2: walking routes
V3: public transport
示例:导航应用中的路线规划功能
V1:道路上的路线
V2:步行路线
V3:公共交通
Strategy: Solution
Extract the algorithms into separate classes: strategies
The client is responsible for selecting the strategy
Switching the strategy is possible at runtime
将算法提取到单独的类中:策略
客户负责选择策略
策略切换是可能在运行时
Template Method: Problem
Example: a data mining application that analyzes documents
Problem 1: a lot of similar code
Problem 2: the client depends on the classes
示例:分析文档的数据挖掘应用程序
问题1:大量类似的代码
问题2:客户端依赖于类
Template Method: Solution
Break down the algorithm into steps
Turn the steps into methods
Call the methods in a single template method
将算法分解为步骤
把步骤变成方法
在单个模板中调用方法