Last active
August 29, 2015 14:09
-
-
Save garudareiga/198c94bae70cb36cf5fe to your computer and use it in GitHub Desktop.
Singleton Design Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Singleton { | |
private Singleton() {} | |
private static class SingletonHolder { | |
private static final Singleton uniqueInstance = new Singleton(); | |
} | |
public static Singleton getInstance() { | |
return SingletonHolder.uniqueInstance; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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