This answer is quite good enter link description here, I'd probably favour an Interface and Implementation but you could still use a Singleton for example:
public interface GraphSource {
public Graph getGraph();
}
public enum DefaultGraph implements GraphSource {
INSTANCE;
private Graph<String,String> graph;
{
graph = new SparseGraph<String,String>();
}
@SuppressWarnings("rawtypes")
@Override
public Graph getGraph() {
return graph;
}
}
public class MyClass {
public MyClass(GraphSource source) {
Graph myGraph = source.getGraph();
}
}
But I'd avoid:
public class MyClass {
GraphSource source = DefaultGraph.INSTANCE;
public MyClass(GraphSource source ) {
Graph myGraph = source.getGraph();
}
}
As it would be hard to Stub or Mock the graph for testing. For a large application I'd consider using Inversion of Control but this would be overkill for a small application if you are not familiar with it.