策略
· 看起来和工厂差别不大,工厂是根据条件返回实例,策略是根据条件发生行为🤷♂️。可应用于分段计价场景,不同计价方式分别作为策略实现
classDiagram
class Strategy {
<<interface>>
+doOperation() void
}
class StrategyA
StrategyA ..|> Strategy : 实现
class StrategyB
StrategyB ..|> Strategy : 实现
class Context {
-Strategy strategy
+execStrategy(Strategy strategy) void
}
Context *-- Strategy : 构造器初始化成员
class Main
Main ..> Context : 实例化
Main ..> StrategyA : 实例化
Main ..> StrategyB : 实例化
· 如果想隐藏实例化过程,那就需要工厂实例化策略
classDiagram
class Strategy {
<<interface>>
+doOperation() void
}
class StrategyA
StrategyA ..|> Strategy : 实现
class StrategyB
StrategyB ..|> Strategy : 实现
class Context {
-Strategy strategy
+execStrategy(Strategy strategy) void
}
Context *-- Strategy : 构造器初始化成员
class StrategyFactory {
<<interface>>
+produceStrategy() Strategy
}
class StrategyFactoryA {
+produceStrategy() StrategyA
}
StrategyFactoryA ..|> StrategyFactory : 实现
StrategyFactoryA ..> StrategyA : 返回
class StrategyFactoryB {
+produceStrategy() StrategyB
}
StrategyFactoryB ..|> StrategyFactory : 实现
StrategyFactoryB ..> StrategyB : 返回
class Main
Main ..> Context : 实例化
Main ..> StrategyFactoryA : 实例化
Main ..> StrategyFactoryB : 实例化