js设计模式 --- 模版设计模式

模版设计模式

设计模式处处透漏者前辈们的指挥, 在众多设计模式中模版设计模式是软件设计中最常用, 最正统的模式, 也是本人最喜欢的模式, 其就像一颗颗螺丝钉处处体现在软件设计和其他模式中

父类定义一个模板结构,将部分具体内容延迟到子类去实现

在软件系统设计中最常用的就是 接口–抽象类–类 三级设计模式, 如下图
《js设计模式 --- 模版设计模式》

模版设计模式结构

再此模式中接口定义了方法, 抽象类定义了算法的框架实现了一部分算法, 对象类则实现了剩余的其他方法(当然如有需要可以灵活配置, 比如抽象类实现了一个默认的方法, 如有需要对象类可以重写这个方法)
《js设计模式 --- 模版设计模式》

实现

  • 接口

    let IEat = new Interface('IEat', ['eatDinner','buy','cook', 'eat'])
  • 抽象类

    let Eatdinner = function () {
    };
    Eatdinner.prototype.buy = function () {
      throw new Error();
    };
    Eatdinner.prototype.cook = function () {
      throw new Error();
    };
    Eatdinner.prototype.eat = function () {
      console.log('吃');
    };
    Eatdinner.prototype.eatDinner = function () {
      this.buy();
      this.cook();
      this.eat();
    };
  • 对象类

    let EatA = function () {
      Eatdinner.call(this);   
    }
    extend(EatA, Eatdinner);
    EatA.prototype.buy = function () {
      console.log('萝卜');
    }
    EatA.prototype.cook = function () {
      console.log('炒');
    }
    
    let EatB = function () {
      Eatdinner.call(this);   
    }
    extend(EatB, Eatdinner);
    EatB.prototype.buy = function () {
      console.log('萝卜');
    }
    EatB.prototype.cook = function () {
      console.log('炸');
    }
    
    let EatC = function () {
      Eatdinner.call(this);   
    }
    extend(EatC, Eatdinner);
    EatC.prototype.buy = function () {
      console.log('青菜');
    }
    EatC.prototype.cook = function () {
      console.log('烤');
    }

模板模式的优点

  • 具体细节步骤实现定义在子类中,子类定义详细处理算法是不会改变算法整体结构。
  • 代码复用的基本技术,在数据库设计中尤为重要。
  • 存在一种反向的控制结构,通过一个父类调用其子类的操作,通过子类对父类进行扩展增加新的行为,符合“开闭原则”。
    原文作者:weixin_33894992
    原文地址: https://blog.csdn.net/weixin_33894992/article/details/88882649
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞