我有以下单身人士
arr_hsh.max_by { |h| h['score'] }
#=> {:name=>"Outdoor", :game_code=>"C5", :score=>"61.68"}
每次我呼叫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
都创建一个新实例?
答案 0 :(得分:0)
我认为您的IOWebSocketChannel.connect
中存在一些无法创建实例的问题。
这是与您类似的代码,除了在创建新实例时使用默认构造函数,并且“创建新通道”仅打印一次。
class Channel {}
class Singleton {
Singleton._();
static final Singleton _instance = Singleton._();
static Singleton get instance => _instance;
Channel _channel;
Channel get channel {
if (_channel == null) {
print("Creating new channel");
_channel = Channel();
}
return _channel;
}
}
void main() {
Singleton.instance.channel;
Singleton.instance.channel;
}
答案 1 :(得分:0)
我认为连接方法存在一些问题,我认为它是静态的,我通过创建类的对象来调用connect,并且它仅作为创建单个实例的原因而工作。
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;
}
}