美文网首页
class单例模式

class单例模式

作者: WWWWWWWWWWWWWWM | 来源:发表于2021-01-22 13:29 被阅读0次
  • 单例模式指的是当用class在生成实例的时候,只会生成一个实例,这个在登录注册弹框,或者WebSocket方面用的比较多

创建class构造函数

//  ./socket_service.js
export default class SocketService {
    /**
     * 单例
     */
    static instance = null;
    static getInstance() {
        if (!this.instance) {
            this.instance = new SocketService()
        };
        return this.instance;
    };
    ws = null;
   
    // 定义连接
    connect() {
        if (!window.WebSocket) {
            alert("您的浏览器不支持websocket");
            return;
        };
       this.ws = new WebSocket('ws://localhost:9998');

    }
}

生成唯一的class 实例

import SocketService from '@/utils/socket_service';
SocketService.getInstance()  生成class实例

//举例子

let a = SocketService.getInstance() ;
let b = SocketService.getInstance() ;
console.log(a === b)   //true   说明a和b指的是同一个实例

相关文章

网友评论

      本文标题:class单例模式

      本文链接:https://www.haomeiwen.com/subject/kmmszktx.html