开发者

Java Singleton - IsEnabled?

Any ideas on a good interface for a singleton with an isEnabled method?

For example, I have a UDPClient and only want to create the Socket once, so I'm setting it up as a singleton. And I want the app to continue if the configuration says to enable it, but it cannot.

Can I do better than this client code and the resulting singleton implementation? (and please correct me if I've screwed up the singleton). This will be used in a web app if it makes any difference.

public class UDPConnectionManager {
    private static final UDPConnectionManager INSTANCE = new UDPConnectionManager();
    private UDPClient udp = null;

    private UDPConnectionManager() {
        try {
            InitialContext ic = new InitialContext();

            String udpHost = (String) ic.lookup("java:comp/env/udpHost");
            Integer udpPort = (Integer) ic.lookup("java:comp/env/udpPort");
            Boolean udpEnabled = (Boolean) ic.lookup("java:comp/env/udpEnabled");

            if (udpEnabled) {
                udp = new UDPClient(udpHost, udpPort);
            }
        } catch (Exception e) {
            log.error("UDP Connection Manager:  e开发者_StackOverflowrror while setting up UDP Manager.", e);
        }
    }

    public static UDPConnectionManager instance() {
        return INSTANCE;
    }

    public UDPClient getUDPClient() {
        return udp;
    }

    public Boolean isEnabled() {
        return (udp != null);
    }
}

Client:

UDPClient udpCM = UDPConnectionManager.instance();
if (udpCM.isEnabled()) {
    UDPClient udpClient = udpcCM.getUDPClient();
    udpClient.send("test");
}


If you expect it to be sort of a fire-and-forget-even-if-its-not-available sort of thing, then you might ease the burden on the client and just put the send() method on the singleton.

By doing this, you can have the singleton do the check, and not send it if it's null.

public class UDPConnectionManager {
    private UDPConnectionManager() { ... }
    public static UDPConnectionManager instance() { ... }

    public void send(String message) {
        if(udp != null) {
            udp.send(message);
        }
    }
}

Don't make the client do anything the module could do (PDF, page 27)


There's nothing wrong with it the way it is per-se, but if all your use cases look like the above then I'd just put a send() method on the singleton and have that decide whether it's enabled or not. If you want to know whether it went through ok, you could have it return a boolean value. Or if you don't want that method on the singleton connection manager, you could write another class that it works through and offload it to that instead.

Of course, if you're planning to use the isEnabled() method to decide on other actions then you may need it available on the singleton anyway and there's nothing wrong with that in my book.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜