Created
August 19, 2015 02:03
-
-
Save dkellycollins/cb9eba29708b1b7725fc to your computer and use it in GitHub Desktop.
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
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); | |
} | |
} |
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
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(); | |
} |
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
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