模板模式(Template Pattern)

当一个类型公开了它的执行方式,其它类型只需按需实现的的时候可以使用这个模式。

模板模式的实例

实现游戏的基类,同时它的执行方式play不允许被子类修改。

  1. class Game {
  2. constructor() {
  3. if(this.play!= Game.prototype.play) {
  4. throw new Error("play mothed is final,can't be modify!");
  5. }
  6. }
  7. initialize(){};
  8. startPlay(){};
  9. endPlay(){};
  10. play(){
  11. //初始化游戏
  12. this.initialize();
  13. //开始游戏
  14. this.startPlay();
  15. //结束游戏
  16. this.endPlay();
  17. }
  18. }

子类只需要通过基类流程中的方法即可

  1. class Cricket extends Game {
  2. endPlay() {
  3. console.log("Cricket Game Finished!");
  4. }
  5. initialize() {
  6. console.log("Cricket Game Initialized! Start playing.");
  7. }
  8. startPlay() {
  9. console.log("Cricket Game Started. Enjoy the game!");
  10. }
  11. }
  12. class Football extends Game {
  13. endPlay() {
  14. console.log("Football Game Finished!");
  15. }
  16. initialize() {
  17. console.log("Football Game Initialized! Start playing.");
  18. }
  19. startPlay() {
  20. console.log("Football Game Started. Enjoy the game!");
  21. }
  22. }

最终都是通过play进行运行

  1. let game = new Cricket();
  2. game.play();
  3. console.log('');
  4. game = new Football();
  5. game.play();
  6. /**
  7. * output:
  8. * Cricket Game Initialized! Start playing.
  9. * Cricket Game Started. Enjoy the game!
  10. * Cricket Game Finished!
  11. *
  12. * Football Game Initialized! Start playing.
  13. * Football Game Started. Enjoy the game!
  14. * Football Game Finished!
  15. */

模板模式的优势

只需要关注自己功能的实现,而不需要着眼整个流程。

上一页(策略模式)

下一页(访问者模式)