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

模板模式的优点

  • 具体细节步骤实现定义在子类中,子类定义详细处理算法是不会改变算法整体结构。
  • 代码复用的基本技术,在数据库设计中尤为重要。
  • 存在一种反向的控制结构,通过一个父类调用其子类的操作,通过子类对父类进行扩展增加新的行为,符合“开闭原则”。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值