Open ChelesteWang opened 2 years ago
单例模式--全局唯一对象 如果没有则创建如果有就返回
function createObj(createMethod) {
let obj;
return function () {
return obj || (obj = createMethod.call(this, arguments));
};
}
let obj = createObj(function () {
return {
name: "obj",
message: "created by createObj",
};
});
适配器模式 -- 用于转换接口
function A() {
return {
A: function () {
return "A";
},
};
}
function B() {
return {
B: function () {
return "B";
},
};
}
function C() {
return {
C: function () {
return "C";
},
};
}
function Word(word) {
return function () {
return {
word: function () {
switch (word) {
case "A":
return A().A();
case "B":
return B().B();
case "C":
return C().C();
}
},
};
};
}
发布订阅模式
class Event {
events = {};
emit(type, ...args) {
const listeners = this.events[type];
for (const listener of listeners) {
listener(...args);
}
}
on(type, listener) {
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}
once(type, listener) {
const callback = (...args) => {
this.off(type, callback);
listener(...args);
};
this.on(type, callback);
}
off(type, listener) {
this.events[type] = this.events[type] || [];
this.events[type] = this.events[type].filter(
(callback) => callback !== listener
);
}
}
策略模式--简化 if else 原理策略对象搭配对象访问