65 lines
1.5 KiB
Dart
65 lines
1.5 KiB
Dart
/**
|
||
策略模式(Strategy Pattern)
|
||
|
||
意图:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
|
||
主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
|
||
何时使用:一个系统有许多许多类,而区分它们的只是他们直接的行为。
|
||
如何解决:将这些算法封装成一个一个的类,任意地替换。
|
||
*/
|
||
main(List<String> args) {
|
||
Context context = new Context(new OperationAdd());
|
||
print("10 + 5 = ${context.executeStrategy(10, 5)}");
|
||
|
||
context = new Context(new OperationSubstract());
|
||
print("10 - 5 = ${context.executeStrategy(10, 5)}");
|
||
|
||
context = new Context(new OperationMultiply());
|
||
print("10 * 5 = ${context.executeStrategy(10, 5)}");
|
||
}
|
||
|
||
//////////////////////////////////////////////////////////////////
|
||
|
||
///
|
||
/// 创建一个接口
|
||
///
|
||
abstract class Strategy {
|
||
int doOperation(int num1, int num2);
|
||
}
|
||
|
||
///
|
||
/// 创建实现接口的实体类
|
||
///
|
||
class OperationAdd implements Strategy {
|
||
@override
|
||
int doOperation(int num1, int num2) {
|
||
return num1 + num2;
|
||
}
|
||
}
|
||
|
||
class OperationSubstract implements Strategy {
|
||
@override
|
||
int doOperation(int num1, int num2) {
|
||
return num1 - num2;
|
||
}
|
||
}
|
||
|
||
class OperationMultiply implements Strategy {
|
||
@override
|
||
int doOperation(int num1, int num2) {
|
||
return num1 * num2;
|
||
}
|
||
}
|
||
|
||
///
|
||
/// 创建 Context 类
|
||
///
|
||
class Context {
|
||
Strategy _strategy;
|
||
|
||
Context(this._strategy);
|
||
|
||
int executeStrategy(int num1, int num2) {
|
||
return _strategy.doOperation(num1, num2);
|
||
}
|
||
}
|