dart_in_action/33_design_pattern_state.dart

65 lines
1.3 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
状态模式State Pattern
意图:允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
主要解决:对象的行为依赖于它的状态(属性),并且可以根据它的状态改变而改变它的相关行为。
何时使用:代码中包含大量与对象状态有关的条件语句。
如何解决:将各种具体的状态类抽象出来。
*/
main(List<String> args) {
Context context = Context();
StartState startState = StartState();
startState.doAction(context);
print(context.state);
StopState stopState = new StopState();
stopState.doAction(context);
print(context.state);
}
//////////////////////////////////////////////////////////////////
///
/// 创建一个接口
///
abstract class State {
void doAction(Context context);
}
///
/// 创建 Context 类
///
class Context {
State state = null;
Context();
}
///
/// 创建实现接口的实体类
///
class StartState implements State {
void doAction(Context context) {
print("Player is in start state");
context.state = this;
}
@override
String toString() {
return "Start State";
}
}
class StopState implements State {
void doAction(Context context) {
print("Player is in stop state");
context.state = this;
}
@override
String toString() {
return "Stop State";
}
}