I have an interface to represent a data structure with competing implementations. I need to use this in a class while decoupling the class from having to know the underlying data structure. And within this class, I will need to create several instances of this implementation. How does one do it using interface injection?
class Foo {
Map<String, IDataStructure> map = new HashMap<String, IDataStructure>();
public void addValue(String key, String value) {
if(!map.containsKey(key)) {
map.put(key, new SomeDataStructure(value));
}
}
}
EDIT
I found out an approach to use interface injection. Create a factory interface
class ADataStructureFactory implements DataStructureFactory {
IDataStructure create() {
return new SomeDataStructure();
}
}
And inject this in the constructor
Foo(DataStuctureFactory factory)
Change the add method
public void addValue(String key, String value) {
if(!map.containsKey(key)) {
map.put(key, factory.create());
}
}