您的位置:首页 > Web前端 > JavaScript

JavaScript设计模式读书笔记(二)=> 结构型设计模式

2020-04-05 07:14 411 查看

全系列目录

  1. JavaScript设计模式读书笔记(一)=> 创建型设计模式
  2. JavaScript设计模式读书笔记(二)=> 结构型设计模式
  3. JavaScript设计模式读书笔记(三)=> 行为型设计模式
  4. JavaScript设计模式读书笔记(四)=> 技巧型设计模式
  5. JavaScript设计模式读书笔记(五)=>架构型设计模式,MVC,MVP,MVVM

文章目录

1. 外观模式

这个很简单,就是指当一个复杂的系统提供一系列复杂的接口方法时,对接口的二次封装隐藏其复杂性。

// e.g.
const api = {
getabc: () => {
// 调用各种函数
// 处理很多
return 'gkd';
}
}

2. 适配器模式

一样很容易理解,将一个对象的方法或者属性转化为另外一个接口,以满足用户的需求,使对象之间接口不兼容问题通过适配器来解决。

// 例如原有一个A框架要换成jq,代码不动就要使用写适配器用jq适配原来的A框架
// e.g.
A.on = function (id, type, fn) {
$('#'+id).on(type, fn);
}

3. 装饰者模式

不改变原对象的基础上,通过对其进行包装拓展使原有对象可以满足用户的更复杂需求。

es6有提供了 http://es6.ruanyifeng.com/#docs/decorator

function doSomething(name) {
console.log('Hello, ' + name);
}

function loggingDecorator(wrapped) {
return function() {
console.log('Starting');
const result = wrapped.apply(this, arguments);
console.log('Finished');
return result;
}
}

const wrapped = loggingDecorator(doSomething);

4. 桥接模式

其最主要的特点是将实现层与抽象层解耦分离,使两部分可以独立变化。

// e.g.
function speed(x, y) {
// 调用很多函数
this.x = x;
this.y = y;
}

speed.prototype.run = function () {
console.log('run');
}

function say(gkd) {
// 调用很多函数
this.word = gkd;
}

say.prototype.speak = function () {
console.log(this.word + ':)');
}

function people (x, y, gkd) {
this.speed = new speed(x, y);
this.mouth = new say(gkd);
}

people.prototype.init = function () {
this.speed.run();
this.mouth.speak();
}

const liu = new people(1,1,'asd');
liu.init();

5. 组合模式

组合模式又称部分-整体模式,将对象组合成树形结构以表示“部分整体”的层次结构。

这个思想和使用React编写组件差不多,不断拆分成最小的功能模板,最后组合到一起

6. 享元模式

享元模式(Flyweight)指运用共享技术有效地支持大量的细粒度对象,避免对象间拥有相同内容造成多余的开销。应用时一定要找准内部状态(数据与方法)与外部状态(数据与方法),这样你才能更合理地提取分离。

这本书的例子代码写的真是渣

下面这个例子就是把移动方法单独抽出来,实现共用,减少其他类重写时造成不必要的开销

const FlyWeight = {
moveX: function(x) {
this.x = x;
},
moveY: function(y) {
this.y = y;
},
}

const Player = function (x, y, name) {
this.x = x;
this.y = y;
this.name = name;
}

// refect写法 Reflect.setPrototypeOf(Player, FlyWeight)

Player.prototype = Object.create(FlyWeight);
Player.prototype.constructor = Player;
Player.prototype.changeName = function (name) {
this.name = name;
};

const Car = function (x, y, logo) {
this.x = x;
this.y = y;
this.logo = logo;
}

// Reflect写法 Reflect.setPrototypeOf(Car, FlyWeight)

Car.prototype = Object.create(FlyWeight);
Car.prototype.constructor = Car;
Car.prototype.changeLogo = function (logo) {
this.logo = logo;
};

参考资料:

  1. 张容铭著 javascript设计模式 68-108页
  • 点赞
  • 收藏
  • 分享
  • 文章举报
刘翾 博客专家 发布了167 篇原创文章 · 获赞 275 · 访问量 59万+ 他的留言板 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: