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

推荐订阅源

J
Java Code Geeks
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
量子位
阮一峰的网络日志
阮一峰的网络日志
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
云风的 BLOG
云风的 BLOG
D
DataBreaches.Net
B
Blog
L
LangChain Blog
Apple Machine Learning Research
Apple Machine Learning Research
Vercel News
Vercel News
博客园 - 三生石上(FineUI控件)
爱范儿
爱范儿
Microsoft Azure Blog
Microsoft Azure Blog
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
B
Blog RSS Feed
H
Help Net Security
The Cloudflare Blog
U
Unit 42

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