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
- javascript设计模式之装饰器模式(结构型模式)
- (8)设计模式之装饰模式(结构型模式)
- 设计模式-结构型之装饰模式
- javascript设计模式之装饰器模式
- 设计模式 结构型设计模式之装饰模式
- 结构型设计模式-装饰器模式
- 【设计模式】结构型模式之装饰器Decorator
- java设计模式(结构型)之装饰模式
- 结构型:设计模式之装饰模式(十一)
- 设计模式之结构型-装饰模式(7)
- Java设计模式概述之结构型模式(装饰器模式)
- Java设计模式之结构型模式-装饰器模式(Decorator)
- OOAD-设计模式(四)结构型模式之适配器、装饰器、代理模式
- java设计模式之结构型模式-装饰模式
- 设计模式 - 结构型模式 - 装饰模式
- 结构型模式之装饰器模式
- 设计模式--装饰器模式Decorator(结构型)
- 设计模式-结构型模式:装饰器模式 Decorator
- 加密算法及概念
- Boost.Interprocess使用手册翻译之六:同步机制(Synchronization mechanisms)
- 等比数列二分求和(首项为0次项与1次项的方法)
- toLowerCase方法
- OSI参考模型中的数据封装及解封装过程
- javascript设计模式之装饰器模式(结构型模式)
- 机器学习-高斯模型
- 如何解决安卓项目报65536错误
- 僵尸进程与孤儿进程
- QQ浏览器9 主页无法修改成功的解决办法
- 103. Binary Tree Zigzag Level Order Traversal | 输出二叉树层次遍历次序
- Boost.Interprocess使用手册翻译之三:一些基本解释 (Some basic explanations)
- 状态机学习笔记(一)
- C++中的类型转换static_cast、dynamic_cast、const_cast和reinterpret_cast总结