《设计模式》 - 5. 适配器模式( Adapter )
来源:互联网 发布:js.users.51.la 编辑:程序博客网 时间:2024/05/21 09:47
适配器模式 (Adapter) :
语言 : JavaScript
以一个游戏主角为例 , 刚开始主角只有(普通攻击)和一个技能(重击) .
//主角var Character = cc.Class.extend({ Attack : function(){ console.log("普通攻击"); }, Skill : function(){ console.log("重击"); }});var character = new Character();character.Attack(); //普通攻击character.Skill(); //重击
当主角到达一定等级 , 转职成了法师 , 攻击方法发生改变 , 普通攻击变成了 (火球) , 技能成了(火雨) . 但是代码中主角的攻击和技能已经写死了 , 这时候再调用 Attack() 和 Skill() 方法肯定会报错 , 遇到这种情况就需要使用适配器模式了 .
//主角var Character = cc.Class.extend({ FireBall : function(){ console.log("火球"); }, FireRain : function(){ console.log("火雨"); }});var character = new Character(); character.Attack(); // 报错 !!!character.Skill(); // 报错 !!!
继承实现 :
通过继承的方式 , 可以使得原代码不改变的情况下可以调用新的方法(技能) .
//适配器var Adapter = Character.extend({ Attack : function(){ this.FireBall(); }, Skill : function(){ this.FireRain(); }});var character = new Adapter();character.Attack(); //火球character.Skill(); //火雨
委派实现 :
通过委派的方式 , 可以使得原代码不改变的情况下可以调用新的方法(技能) .
//适配器var Adapter = cc.Class.extend({ character : null, //构造函数 ctor ctor : function(character){ this.character = character; }, Attack : function(){ this.character.FireBall(); }, Skill : function(){ this.character.FireRain(); }});var character = new Adapter(new Character());character.Attack(); //火球character.Skill(); //火雨
适配器模式通常在多人合作的项目中使用较多 , 在多人合作项目中 , 每个人完成自己的模块 , 通常会出现方法名 调用以自己习惯的方式命名 , 从而出现对接问题 , 又因为项目中高频出现 , 不方便修改 , 所以经常使用适配器 .
1 0
- 设计模式--适配器(Adapter)
- 适配器Adapter 设计模式
- 设计模式--Adapter(适配器)
- 设计模式 - 适配器(Adapter)
- 适配器设计模式-Adapter
- Adapter(适配器)设计模式
- Adapter-适配器设计模式
- 设计模式:adapter适配器
- 《设计模式》 - 5. 适配器模式( Adapter )
- 设计模式--适配器模式(Adapter)
- 设计模式--适配器模式(Adapter)
- [设计模式]Adapter适配器模式
- 设计模式-适配器模式(adapter)
- 设计模式 -- Adapter 适配器模式
- 设计模式 - 适配器模式 Adapter
- 设计模式--适配器模式Adapter
- 设计模式:适配器模式-adapter
- 设计模式-适配器模式(Adapter)
- eclipse快捷键
- JavaWeb中获取资源文件路径
- 06
- Android 中的 WebView实现Html5视屏标签
- 用xlwings实现Call Python from Excel
- 《设计模式》 - 5. 适配器模式( Adapter )
- 利用日期正则表达式之识别合法日期
- postgresql 游标简单例子
- CoreText入门
- mysql 报错:Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65
- MonkeyKing canOpenURL: failed for URL: "weixin://" - error: "The operation couldn’t be completed. (O
- 基数排序
- S4.6_Struts2_Annotation action动作类使用annotation注解的配置方式
- webview控件介绍