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

模版设计模式

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

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

在软件系统设计中最经常使用的就是 接口--抽象类--类 三级设计模式, 以下图
图片描述java

模版设计模式结构

再此模式中接口定义了方法, 抽象类定义了算法的框架实现了一部分算法, 对象类则实现了剩余的其余方法(固然若有须要能够灵活配置, 好比抽象类实现了一个默认的方法, 若有须要对象类能够重写这个方法)
图片描述算法

实现

  • 接口数据库

    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('烤');
    }

模板模式的优势数据库设计

  • 具体细节步骤实现定义在子类中,子类定义详细处理算法是不会改变算法总体结构。
  • 代码复用的基本技术,在数据库设计中尤其重要。
  • 存在一种反向的控制结构,经过一个父类调用其子类的操做,经过子类对父类进行扩展增长新的行为,符合“开闭原则”。
相关文章
相关标签/搜索