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

推荐订阅源

量子位
Stack Overflow Blog
Stack Overflow Blog
人人都是产品经理
人人都是产品经理
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Y
Y Combinator Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
博客园 - 司徒正美
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
L
LangChain Blog

博客园 - 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)  评论()    收藏  举报