单例模式
const SinglePerson = (function () {
let instance = null;
class Person {
constructor({ name, age }) {
this.name = name;
this.age = age;
this.callback = () => {};
this.setEvent();
}
setEvent() {
window.addEventListener("click", e => {
this.callback(e);
});
}
}
return function (options, callback) {
if (!instance) {
instance = new Person(options);
}
instance.callback = callback;
return instance;
};
})();
const p1 = SinglePerson(
{
name: "张三",
age: 25,
},
res => {
console.log("p1", res);
}
);
const p2 = SinglePerson({}, res => {
console.log("p2", res);
});
console.log(p1);
console.log(p2);
console.log(p1 === p2);
观察者模式
class Observer {
constructor(name, fn = () => {}) {
this.name = name;
this.fn = fn;
}
}
class Observable {
constructor(state) {
this.state = state;
this.observerList = [];
}
setState(state) {
this.state = state;
this.observerList.forEach(item => {
item.fn(state);
});
}
addObserver(observer) {
this.observerList = [...new Set([...this.observerList, observer])];
}
deleteObserver(observer) {
this.observerList = this.observerList.filter(item => item !== observer);
}
}
const bzr = new Observer("班主任", state => {
console.log(`又${state}, 不好好学习`);
});
const jz = new Observer("家长", state => {
console.log(`又${state}, 你看看别人家的那XX学习多好`);
});
const njzr = new Observer("年级主任", state => {
console.log(`又${state}, 你是哪个班的`);
});
const xiaoming = new Observable("学习");
xiaoming.addObserver(bzr);
xiaoming.addObserver(jz);
xiaoming.addObserver(njzr);
xiaoming.setState("玩手机");