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

来源:互联网 发布:水量伺服器 知乎 编辑:程序博客网 时间:2024/06/14 14:07

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!
0 0
原创粉丝点击