dart_in_action/36_design_pattern_template....

76 lines
1.5 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.

/**
模板模式Template Pattern
意图:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
主要解决:一些方法通用,却在每一个子类都重新写了这一方法。
何时使用:有一些通用的方法。
如何解决:将这些通用算法抽象出来。
*/
main(List<String> args) {
Game game = new Cricket();
game.play();
print('');
game = new Football();
game.play();
}
//////////////////////////////////////////////////////////////////
///
/// 创建一个抽象类
///
abstract class Game {
void initialize();
void startPlay();
void endPlay();
//模板
void play() {
//初始化游戏
initialize();
//开始游戏
startPlay();
//结束游戏
endPlay();
}
}
///
/// 创建扩展了上述类的实体类
///
class Cricket extends Game {
@override
void endPlay() {
print("Cricket Game Finished!");
}
@override
void initialize() {
print("Cricket Game Initialized! Start playing.");
}
@override
void startPlay() {
print("Cricket Game Started. Enjoy the game!");
}
}
class Football extends Game {
@override
void endPlay() {
print("Football Game Finished!");
}
@override
void initialize() {
print("Football Game Initialized! Start playing.");
}
@override
void startPlay() {
print("Football Game Started. Enjoy the game!");
}
}