1、装饰器模式 ?
1、介绍
- 装饰器内 会先取得之前的功能 再添加功能
- 使用时需要将 原来的实例 传入 装饰器中
- 动手试试
写代码 理解一下
class Circle {
draw() {
console.log("画一个五角星");
}
}
class Decorator {
constructor(circle) {
this.circle = circle;
}
draw() {
this.circle.draw(); // 原来的功能
this.setRedBoard(circle); // 新增的装饰器功能
}
setRedBoard(circle) {
console.log("画一个三角形");
}
}
// 测试代码
// 先看自身功能
let circle = new Circle();
circle.draw();
console.log("---分割线---");
//装饰器功能
let dec = new Decorator(circle);
dec.draw();
- 实现效果
2、使用场景展示
装饰器 使用 场景 展示
- 安装插件
yarn add babel-plugin-transform-decorators-legacy --save-dev
尝试 写 es7 装饰器
理解一下 原理
还可 传递 参数
还可 使用 mixin
3、装饰器 方法
1、readonly
- 代码展示
2、打印 日志
3、core-decorator 第三方库 比较好用
- 安装 yarn add core-decorators --save
- 设计原则
2、外观模式 ?
3、观察者模式(重点 ) ?
1、介绍
2、代码展示
// 观察者模式
// 主题 保存状态 当状态 变化后 通知 观察者 对象
class Subject {
constructor() {
this.state = 0;
this.observers = [];
}
getState() {
return this.state;
}
setState(state) {
this.state = state;
this.notifyAllObservers();
}
notifyAllObservers() {
this.observers.forEach((observer) => {
observer.update();
});
}
attach(observer) {
this.observers.push(observer);
}
}
// 观察者
class Observer {
constructor(name, subject) {
this.name = name;
this.subject = subject;
this.subject.attach(this); // 将自己 作为观察者 传入 主题中
}
update() {
console.log(`${this.name} update, state: ${this.subject.getState()}`);
}
}
// 测试
let s = new Subject();
let o1 = new Observer("o1", s);
let o2 = new Observer("o2", s);
let o3 = new Observer("o3", s);
s.setState(1);
- 结果展示
主题的setState使得 state更改时,通知观察者 状态 已经更新
3、重要的 使用 场景
-
网页 事件绑定 -
Promise
jQuery callbacks
nodejs自定义事件
1、自定义事件
2、 还有一个 继承
3、读取大文件时 使用的文件流
4、读取文件有多少行
- 我们去检查一下 文件 看对不对
4、其他 场景
5、 设计原则验证