Kaynağa Gözat

chore:Singleton

Paul 5 yıl önce
ebeveyn
işleme
6e1402ab85
2 değiştirilmiş dosya ile 17 ekleme ve 13 silme
  1. 1
    1
      example/main.ts
  2. 16
    12
      src/index.ts

+ 1
- 1
example/main.ts Dosyayı Görüntüle

@@ -2,7 +2,7 @@ import { Client } from '../src/';
2 2
 import { WebsocketError, WebSocketResp } from '../src/types';
3 3
 
4 4
 const url = 'ws://127.0.0.1:8081';
5
-const client = new Client(url, {
5
+const client = Client.getInstance(url, {
6 6
   onOpen(): void {
7 7
     client
8 8
       .ping({})

+ 16
- 12
src/index.ts Dosyayı Görüntüle

@@ -14,6 +14,7 @@ const clientError = 400;
14 14
 class Client {
15 15
   private _maxPayload: number;
16 16
   private _enableLogger: boolean;
17
+  private static instance: Client;
17 18
   private listeners: Map<number, (data: WebSocketResp) => void>;
18 19
   private requestHeader: string;
19 20
   private responseHeader: string;
@@ -28,7 +29,7 @@ class Client {
28 29
    * @param url websocket链接地址
29 30
    * @param readyStateCallback 链接状态回调,可以处理onOpen、onClose、onError
30 31
    */
31
-  public constructor(url: string, readyStateCallback: ReadyStateCallback) {
32
+  private constructor(url: string, readyStateCallback: ReadyStateCallback) {
32 33
     this.listeners = new Map<number, (data: WebSocketResp) => void>();
33 34
     this.requestHeader = '';
34 35
     this.requestHeader = '';
@@ -40,6 +41,19 @@ class Client {
40 41
     this.socket = this.connect();
41 42
   }
42 43
 
44
+  /**
45
+   * 通过单例模式获取客户端链接
46
+   * @param url websocket链接地址
47
+   * @param readyStateCallback 链接状态回调,可以处理onOpen、onClose、onError
48
+   */
49
+  public static getInstance(url: string, callback: ReadyStateCallback): Client {
50
+    if (!Client.instance) {
51
+      Client.instance = new Client(url, callback);
52
+    }
53
+
54
+    return Client.instance;
55
+  }
56
+
43 57
   /**
44 58
    * 设置可以处理的数据包上限
45 59
    * @param maxPayload 最多可以处理的数据包大小
@@ -417,14 +431,4 @@ class Client {
417 431
   }
418 432
 }
419 433
 
420
-let client: Client;
421
-
422
-function getClient(url: string, callback: ReadyStateCallback): Client {
423
-  if (!client) {
424
-    client = new Client(url, callback);
425
-  }
426
-
427
-  return client;
428
-}
429
-
430
-export { Client, getClient };
434
+export { Client };