开发者

How to initialize my singleton object

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;
    }
}
  1. Is it ok to initialize client in the above fashion.
  2. Should I declare private Foo foo; as static, I am guessing its not the case.
  3. 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.


  1. Yes. In the constructor you can check if client != null and if it is - throw an error. (this will counter reflection instantiations)

  2. No, it is an instance field of the singleton

  3. 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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜