-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
设计模式 #43
Comments
单例模式--全局唯一对象 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
);
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
策略模式--简化 if else
原理策略对象搭配对象访问
The text was updated successfully, but these errors were encountered: