javascript设计模式之装饰器模式(结构型模式)

javascript设计模式之装饰器模式

js的设计模式分为创建型模式,结构型模式和行为模式

结构模式描述了如何组合对象以提供新的功能。

装饰器模式是一种常见的结构型模式,我们可以以一个基础对象为基础,来给它加上若干个装饰对象以拓展其功能。

下面是示例代码:

首先我想给一颗圣诞树上装饰很多小东西,也就是大概实现这个方法:

var tree = {
  decorate:function (){
    console.log('make some decorates on the tree!');
  }
};

tree.getDecorate('RedBall');
tree.getDecorate('Angle');
tree.getDecorate('BlueBall');

tree.decorate();

我们需要给这个tree方法加一些装饰器,装饰器该怎么写呢?

tree.getDecorate = function (deco){
  tree[deco].prototype = this;
  return new tree[deco];
};

tree.RedBall = function (){
  this.decorate = function (){
    this.RedBall.prototype.decorate();
    alert('add a redball on the tree!');
  }
};

tree.BlueBall = function (){
  this.decorate = function (){
    this.BlueBall.prototype.decorate();
    alert('add a blueball on the tree!');
  }
};

tree.Angle = function (){
  this.decorate = function (){
    this.Angle.prototype.decorate();
    alert('there is an anggle on the tree now!');
  }
};
写完装饰器,我们就可以将这些装饰器装到这课圣诞树上面了!
tree.getDecorate('RedBall');
tree.getDecorate('BlueBall');
tree.getDecorate('Angle');

tree.decorate();
看看console的结果:
make some decorates on the tree!
add a redball on the tree!
add a blueball on the tree!
there is an anggle on the tree now!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值