public class FooClient {
private Foo foo;
private final static String key = "<api-key>";
p开发者_StackOverflow社区rivate 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.
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.
Usually you declare
private static final FooClient client = new FooClient();
This is the traditional Singleton implementation. See wikipedia page for other implementation options.
I would not declare Foo foo
as static
.
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.
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.
enum FooClient {
INSTANCE;
private final Foo foo = new Foo("<api-key>");
}
for the case where there is more than one.
enum FooClient {
INSTANCE1("<api-key>"), INSTANCE2("<api-key2>");
private final Foo foo;
FooClient(String apiKey) {
foo = new Foo(apiKey);
}
}
精彩评论