首页 > 解决方案 > 颤振中的单例模式

问题描述

我有以下单身人士

class WebSocketSingleton {

   IOWebSocketChannel _channel;

   WebSocketSingleton._privateConstructor();

   static final WebSocketSingleton _instance = WebSocketSingleton._privateConstructor();

   static WebSocketSingleton get instance => _instance;

   IOWebSocketChannel get channel{
   if(_channel == null){
      debugPrint("Creating new channel");
      _channel =  IOWebSocketChannel.connect(
         "wss://42zn68xb57.execute-api.us-east-1.amazonaws.com/Test");
    }

    return _channel;
   }
}

每次我调用WebSocketSingleton.instance它都会创建一个新的IOWebSocketChannel.

问题:

每次调用时不应该WebSocketSingleton返回以前创建的实例而不是创建一个新实例吗?IOWebSocketChannelWebSocketSingleton.instance

标签: flutterdartsingleton

解决方案


I think there is some issue with a connecting method which I guess it's static, I am calling connect by creating object of the class, and it's working as the only a single instance is created.

void main() {
  WebSocketSingleton.instance.channel;
  WebSocketSingleton.instance.channel;
  WebSocketSingleton.instance.channel;
}



class WebSocketSingleton {

  IOWebSocketChannel _channel;

  WebSocketSingleton._privateConstructor();

  static final WebSocketSingleton _instance = WebSocketSingleton._privateConstructor();

  static WebSocketSingleton get instance => _instance;

  IOWebSocketChannel get channel{
    if(_channel == null){
      debugPrint("Creating new channel");
      _channel =  IOWebSocketChannel().connect(
          "wss://42zn68xb57.execute-api.us-east-1.amazonaws.com/Test");
    }

    return _channel;
  }
}

class IOWebSocketChannel {
  IOWebSocketChannel connect(String url) {
    return this;
  }
}

推荐阅读