Skip to content

Instantly share code, notes, and snippets.

@garudareiga
Last active August 29, 2015 14:09
Show Gist options
  • Save garudareiga/198c94bae70cb36cf5fe to your computer and use it in GitHub Desktop.
Save garudareiga/198c94bae70cb36cf5fe to your computer and use it in GitHub Desktop.
Singleton Design Pattern
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton uniqueInstance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.uniqueInstance;
}
}
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Map<String, String> kvmap = new ConcurrentHashMap(new HashMap<String, String>());
private Singleton() {}
public static Singleton getInstance { return uniqueInstance; }
public String getValue(String key) { return kvmap.get(key); }
public Set<String> getKeys() { return kvmap.keySet(); }
}
public interface ServerInterface {
public void config(String[] params);
}
public class ServerSingleton implements ServerInterface {
private ServerSingleton() {}
private static class SingletonHolder {
private static final ServerSingleton uniqueInstance = new ServerSingleton();
}
public static ServerSingleton getInstance() {
return SingletonHolder.uniqueInstance;
}
public void config(String[] params) {
// ...
}
}
public class Client {
private final ServerInterface server;
public Client(ServerInterface server) {
this.server = server;
}
public void configServer(String[] params) {
this.server.config(params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment