flutter - 颤振中的单例模式
问题描述
我有以下单身人士
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
返回以前创建的实例而不是创建一个新实例吗?IOWebSocketChannel
WebSocketSingleton.instance
解决方案
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;
}
}
推荐阅读
- node.js - Google oauth20 匿名回调函数未在 passport.use 块中执行
- visual-studio-code - 如何在vim中为vscode向上或向下移动当前行
- python - python:初学者不理解结果:将列表附加到一个类
- angular - PrimeNg 树:当我单击按钮以在父/子节点上打开模式时,复选框选择被取消选择
- mysql - mysql 从多个表创建视图
- c - 在循环中添加和除数时错误的小数结果
- python - 如何从image_URL下载图像并计算python中的重复次数?
- javascript - 选择选项后无法使用 jQuery 禁用输入元素
- ruby-on-rails - 如何将列类型从整数更改为小数,小数点后有一个字母?
- postgresql - 在 Postgresql 12 中,主服务器数据发生故障和从服务器故障转移时会发生什么情况?