Browse Source

chore:Singleton

Paul 5 years ago
parent
commit
6e1402ab85
2 changed files with 17 additions and 13 deletions
  1. 1
    1
      example/main.ts
  2. 16
    12
      src/index.ts

+ 1
- 1
example/main.ts View File

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

+ 16
- 12
src/index.ts View File

14
 class Client {
14
 class Client {
15
   private _maxPayload: number;
15
   private _maxPayload: number;
16
   private _enableLogger: boolean;
16
   private _enableLogger: boolean;
17
+  private static instance: Client;
17
   private listeners: Map<number, (data: WebSocketResp) => void>;
18
   private listeners: Map<number, (data: WebSocketResp) => void>;
18
   private requestHeader: string;
19
   private requestHeader: string;
19
   private responseHeader: string;
20
   private responseHeader: string;
28
    * @param url websocket链接地址
29
    * @param url websocket链接地址
29
    * @param readyStateCallback 链接状态回调,可以处理onOpen、onClose、onError
30
    * @param readyStateCallback 链接状态回调,可以处理onOpen、onClose、onError
30
    */
31
    */
31
-  public constructor(url: string, readyStateCallback: ReadyStateCallback) {
32
+  private constructor(url: string, readyStateCallback: ReadyStateCallback) {
32
     this.listeners = new Map<number, (data: WebSocketResp) => void>();
33
     this.listeners = new Map<number, (data: WebSocketResp) => void>();
33
     this.requestHeader = '';
34
     this.requestHeader = '';
34
     this.requestHeader = '';
35
     this.requestHeader = '';
40
     this.socket = this.connect();
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
    * @param maxPayload 最多可以处理的数据包大小
59
    * @param maxPayload 最多可以处理的数据包大小
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 };