Rumah > hujung hadapan web > tutorial js > js装饰设计模式学习心得(详细解答)

js装饰设计模式学习心得(详细解答)

亚连
Lepaskan: 2018-05-18 16:57:44
asal
1455 orang telah melayarinya

本片文章给大家分享一下作者学习Javascript装饰设计模式后的心得以及要点分享,有兴趣的朋友参考下。

装饰设计模式

每种设都有其独特的应用场景和解决问题的方式, 装饰设计模式是动态的为对象添加新的功能, 是一种用于代替继承的技术,无需通过继承增加子类就能扩展对象的新功能。使用对象的关联关系代替继承关系,更加灵活,同时避免类型体系的快速膨胀, 这种模式适合新添加的功能不足以用继承为代价解决问题的情况时使用 - 杀鸡焉用宰牛刀 ^_^
装饰设计模式: 动态地为一个对象添加一些额外的职责,若要扩展一个对象的功能,装饰者提供了比继承更有弹性的替代方案。

结构图:

接口

var Bicycle = new Interface('Bicycle', ['assemble', 'wash', 'repair', 'getPrice']);
Salin selepas log masuk

对象类

var AcmeComfortCuiser = function(){
};
AcmeComfortCuiser.prototype = {
  assemble: function(){
  },
  wash: function(){
  },
  repair: function(){
  },
  getPrice: function(){
  }
}
Salin selepas log masuk

装饰类

var BicycleDecorator = function(bicycle){
  Interface.ensureImplements(bicycle, Bicycle);
  this.bicycle = bicycle;
};
BicycleDecorator.prototype = {
  assemble: function(){
    return this.bicycle.assemble();
  },
  wash: function(){
    return this.bicycle.wash();
  },
  repair: function(){
    return this.bicycle.repair();
  },
  getPrice: function(){
    return this.bicycle.getPrice();
  }
}
Salin selepas log masuk

拓展类

  var HeadlightDecorator = function(bicycle){
    BicycleDecorator.call(this, bicycle);
  };
  extend(HeadlightDecorator, BicycleDecorator);
  HeadlightDecorator.prototype.getPrice = function(){
    return this.bicycle.getPrice() + 15.00;
  }
Salin selepas log masuk

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用JS回调函数案例说明

使用JS回调函数案例说明

nodejs搭建本地服务器处理跨域

Atas ialah kandungan terperinci js装饰设计模式学习心得(详细解答). Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan