1. 程式人生 > >javascript設計模式之裝飾器模式(結構型模式)

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!