Skip to content

Instantly share code, notes, and snippets.

@akx
Created November 5, 2012 20:04
Show Gist options
  • Save akx/4020023 to your computer and use it in GitHub Desktop.
Save akx/4020023 to your computer and use it in GitHub Desktop.
Abstract Singleton Cache Factory
package hurrdurrtest;
public class AwesomeService extends ServiceBase {
private String context;
@Override
public void setContext(String ctx) {
System.out.println("Yo, the context is " + ctx);
context = ctx;
}
public AwesomeService() {
System.out.println("AwesomeService instantiated.");
}
void shoutThineContext() {
System.out.println(context.toUpperCase() + " IS MY CONTEXT.");
}
}
AwesomeService instantiated.
Yo, the context is derpy hooves
DERPY HOOVES IS MY CONTEXT.
Yo, the context is herpy doves
HERPY DOVES IS MY CONTEXT.
Pretty sure no new instance was created. All good
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hurrdurrtest;
public class HurrDurrTest {
public static void main(String[] args) {
try {
AwesomeService srv1 = null;
AwesomeService srv2 = null;
srv1 = ServiceManager.get(AwesomeService.class, "derpy hooves");
srv1.shoutThineContext();
srv2 = ServiceManager.get(AwesomeService.class, "herpy doves");
srv2.shoutThineContext();
if(srv1 == srv2) System.out.println("Pretty sure no new instance was created. All good");
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
}
}
}
package hurrdurrtest;
public abstract class ServiceBase {
public abstract void setContext(String ctx);
}
package hurrdurrtest;
import java.util.HashMap;
public class ServiceManager {
private static HashMap<Class, ServiceBase> cache = new HashMap<Class, ServiceBase>();
public static <T extends ServiceBase> T get(Class<T> klass, String ctx) throws InstantiationException, IllegalAccessException {
T inst = null;
if(cache.containsKey(klass)) {
inst = (T)cache.get(klass);
} else {
cache.put((Class)klass, inst = (T)klass.newInstance());
}
inst.setContext(ctx);
return inst;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment