概念
確保某個(gè)方法或者類(lèi)只有一個(gè)是咧。而且自行實(shí)例子并向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-755740.html
要點(diǎn)
- 某個(gè)方法或類(lèi)只能一個(gè);
- 必須自行創(chuàng)建這個(gè)實(shí)例
- 必須自行向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。
UML
javascript 實(shí)現(xiàn)代碼
const Singleton = (function() {
let instance;
function createInstance() {
// 在這里可以放一些初始化邏輯
return {
someMethod: function() {
// 添加單例的方法和邏輯
}
};
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 使用單例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // 輸出 true,因?yàn)樗鼈兪峭粋€(gè)實(shí)例
typescript 實(shí)現(xiàn)代碼
class Singleton {
private static instance: Singleton | null = null;
private constructor() {
// 這里可以放一些初始化邏輯
}
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Proxy(new Singleton(), {
get: function(target, prop, receiver) {
if (prop === 'instance') {
return undefined; // 防止通過(guò) instance 直接訪問(wèn)實(shí)例
}
return Reflect.get(target, prop, receiver);
}
});
}
return Singleton.instance as Singleton;
}
public someMethod() {
// 在這里添加單例的方法和邏輯
}
}
// 使用單例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // 輸出 true,因?yàn)樗鼈兪峭粋€(gè)實(shí)例
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-755740.html
到了這里,關(guān)于單例模式——javascript和typescript的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!