惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Last Week in AI
Last Week in AI
D
DataBreaches.Net
腾讯CDC
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
云风的 BLOG
云风的 BLOG
罗磊的独立博客
月光博客
月光博客
MyScale Blog
MyScale Blog
U
Unit 42
Martin Fowler
Martin Fowler
Stack Overflow Blog
Stack Overflow Blog
T
Tailwind CSS Blog
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
G
Google Developers Blog
博客园 - 【当耐特】
D
Docker
I
InfoQ
雷峰网
雷峰网

博客园 - howhy

TypeScript any vs unknown 详细对比 TypeScript interface vs type 完整对比 html 元素包含关系 this 指向 空对象 Object.keys for ...in Reflect.ownKeys ...区别 逻辑运算符和空值运算符 运算符优先级 js 类型显式转换 js 高级函数 js 方法重载 fetch timeout js 任务顺序执行 暂停 js 并发任务 判断两个对象是否相同 js 动态拦截属性 js 通用动画 js groupby js 防抖和节流 实现 instanceof 操作符 js 数组去重和扁平方法 js 继承方法 js new的过程实现 js deepCopy js '=='的隐性类型转换规则
js 单例模式
howhy · 2025-12-29 · via 博客园 - howhy
class Singleton {
    // 1. 使用私有静态属性
    static #instance = null;
    
    // 2. 防止直接 new
    constructor() {
        if (Singleton.#instance) {
            throw new Error('Use getInstance() instead of new');
        }
        Singleton.#instance = this;
        // 初始化逻辑
        this.initialized = false;
    }
    
    // 3. 获取单例实例
    static getInstance() {
        if (!Singleton.#instance) {
            Singleton.#instance = new Singleton();
        }
        return Singleton.#instance;
    }
    
    // 4. 添加实际的方法
    initialize(config) {
        if (!this.initialized) {
            this.config = config;
            this.initialized = true;
        }
    }
    
    // 5. 业务方法...
}

posted @ 2025-12-29 14:06  howhy  阅读(49)  评论()    收藏  举报