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: error 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.
Don’t make the client do anything the module could do (PDF, page 27)