0

Actually , I use jung library to construct my hyper graph.

I want to use only one instance of hyper graph all over my application so that I can't access it and mofify it from any class in my application (to add vertex, to add a hyperEdge, etc.).

It is possible ?

I try to use the singleton pattern but as far as I read in this question it is not a good choice.

Community
  • 1
  • 1
nawara
  • 1,157
  • 3
  • 24
  • 49
  • Why would Singleton not be a good choice for this? Can you please update the link? – CodeBlue Apr 25 '13 at 17:17
  • It's not that the Singleton itself is so much of a bad choice - just what it represents. The idea of having something accessible throughout your entire application means that it is essentially a global variable. When something goes wrong and you have to debug your program, you now have to check _all_ of your program because any class could have modified your graph. You might want to rethink if every part of your program actually needs access to your graph. – sdasdadas May 08 '13 at 13:59

1 Answers1

0

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.

Community
  • 1
  • 1
GrahamA
  • 5,875
  • 29
  • 39