02 Javascript创建型设计模式之 - 单例模式

待兔
• 阅读 874

1. 什么是单例模式?

单例,从名字就知道,就一个呗,说白了就是整个进程中,只有一个类的对象 这样有什么好处吗?当然是有的,整个进程就只有一个该类的对象的话,是不是很省内存

在任何地方都可以访问,比如全局配置就可以做成一个单例模式。

我们以 ES6 语法为例,来写一个单例的代码

'use strict'

class AppleCompany {
    constructor(name, creator, products) {
        this.name = name;
        this.creator = creator;
        this.products = products;
    }

    //静态方法
    static getInstance() {
        if(!this.instance) {
            this.instance = new AppleCompany();
        }
        return this.instance;
    }

    //业务方法
    show(){
        console.log('苹果公司只有一个')
    }
  }

 //获取对象的时候,只通过 getInstance()方法获取
 let company = AppleCompany.getInstance()
 company.show() 

单例的应用场景

比如全局的配置类,就可以作为一个单例类,在程序的任何地方都可以用到

点赞
收藏
评论区
推荐文章

暂无数据