如何初始化我的单例对象
public class FooClient {
private Foo foo;
private final static String key = "<api-key>";
private static FooClient client = new FooClient();
private FooClient() {
foo = new Foo(key);
}
public static FooClient getFooClient() {
return client;
}
}
- 以上述方式初始化
client
可以吗? - 我应该声明 private Foo foo;作为静态,我猜情况并非如此。
- 如果我必须支持不同键的不同单例,我是否应该修改 getFooClient(String key) 来获取键并缓存它,以便我可以返回特定于键的单例 FooClient。
public class FooClient {
private Foo foo;
private final static String key = "<api-key>";
private static FooClient client = new FooClient();
private FooClient() {
foo = new Foo(key);
}
public static FooClient getFooClient() {
return client;
}
}
- Is it ok to initialize
client
in the above fashion. - Should I declare private Foo foo; as static, I am guessing its not the case.
- If I have to support different singletons for different keys, should I modify
getFooClient(String key)
to take in a key and cache it, so that I can return singleton FooClients which are key specific.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常你声明
这是传统的单例实现。有关其他实施选项,请参阅维基百科页面。
我不会将
Foo foo
声明为static
。如果您的单例可以根据键返回不同的实例,那么最好在
getFooClient()
方法中传递键值。Usually you declare
This is the traditional Singleton implementation. See wikipedia page for other implementation options.
I would not declare
Foo foo
asstatic
.If your singleton can return different instances based on the key, then it's a good idea to pass the key value in the
getFooClient()
method.如果你有不止一个东西,它就不是单例。
在这两种情况下我都会使用
enum
。对于只有一个的情况。
对于有多个的情况。
If you have more than one of something, its not a singleton.
I would use
enum
in both cases.For the case where this is just one.
for the case where there is more than one.
是的。在构造函数中,您可以检查是否
client != null
,如果是,则抛出错误。 (这将对抗反射实例化)不,它是单例的实例字段
是。并且您应该有一个
Map
。但请注意,这不是“不同的单身人士” - 您的单身人士是“客户端”。其他类可以多次实例化。Yes. In the constructor you can check if
client != null
and if it is - throw an error. (this will counter reflection instantiations)No, it is an instance field of the singleton
Yes. And you should have a
Map<String, Foo>
. But note that that is not "different singletons" - your singleton is the "client". The other classes can be instantiated multiple times.