Skip to content

Instantly share code, notes, and snippets.

@dkellycollins
Created August 19, 2015 02:03
Show Gist options
  • Save dkellycollins/cb9eba29708b1b7725fc to your computer and use it in GitHub Desktop.
Save dkellycollins/cb9eba29708b1b7725fc to your computer and use it in GitHub Desktop.
package com.dkellycollins.ioc;
import java.util.HashMap;
import java.util.Map;
/**
* Manages class instances.
*/
public abstract class Module {
private Map<String, Provider> _registry;
public Module() {
_registry = new HashMap<String, Provider>();
}
public <T> T get(String key) {
if(_registry.containsKey(key)) {
return (T) _registry.get(key).getInstance();
}
return null;
}
protected void init() {}
protected void register(String key, Provider provider) {
_registry.put(key, provider);
}
protected <T> Provider<T> singleton(Provider<T> provider) {
return new SingletonProvider<T>(provider);
}
}
package com.dkellycollins.ioc;
/**
* Represents a class that can provide an instance of another class.
*/
public interface Provider<T> {
/**
* Returns an instance of the class.
* @return
*/
T getInstance();
}
package com.dkellycollins.ioc;
/**
* Manages a single instance of a class.
* @param <T> The type of the class.
*/
class SingletonProvider<T> implements Provider<T> {
private final Provider<T> _inner;
private T _instance;
public SingletonProvider(Provider<T> inner) {
_inner = inner;
}
@Override
public T getInstance() {
if(_instance == null) {
_instance = _inner.getInstance();
}
return _instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment