Reputation: 375
Problem to solve: give a priority (int value) to all the nodes of a graph. There is a DAG class with an attribute Graph (of type DirectedGraph from JGraphT library). Moreover, there must be different algorithms to assign priorities, and it must be possible to add new algorithms in the future without modifying the existing code. The DAG is created first, and then the user will have the possibility to select which algorithm to use (using a ComboBox in a GUI). The user must have the possibility to change the algorithm at any moment.
Approach 1: Develop an interface (Algorithm) for the algorithms, and make all the algorithms implement that interface. In the DAG class, add a new attribute:
Algorithm myAlgo;
Each time the user selects a different algorithm on the GUI, instantiate that algorithm:
myAlgo = new AlgorithmNumberX;
Approach 2: Write the prioritization task independently (not as an attribute of the DAG), use a static method to prioritize the nodes of the DAG, by sending the DAG as an argument and returning the modified DAG.
Which advantages has each approach?
Upvotes: 0
Views: 778
Reputation: 11733
Why did you put the Design Patterns tag on this and then not mention them at all?
This is clearly a job for the Strategy Pattern.
The other thing worth thinking about here is genericizing the graph itself, so having a way to do Graph. That way you could have graphs of anything and be able to score them at will.
The other question here is what is the purpose of this scoring? Ordering, right? So you are basically producing an index, no? And you might want to have other orderings? So some organization where you could contain different orders in groups together would make sense, then you could presumably switch between them without an intervening rebuild (as you mention).
Upvotes: 1
Reputation: 866
I would personally go for option 1 (as I recently have). You are basically describing a Strategy pattern (a combination of both options actually). The only problematic thing you may have with that approach is getting the class names to enter into the combo box. You will also need to add an object that creates the instance for you. if you do new Algorithmx you will need to add another such statement for each algorithm you add which is against the requirements you stated.
public class AlgorithmStrategy
{
public static final Algorithm getAlgorithm(String className)
{
Algorithm algorithm = null;
String name = "<package algorithms are in>." + className;
try
{
algorithm = (Algorithm)Class.forName(name).newInstance();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
e.printStackTrace();
}
return algorithm;
}
}
In this example Algorithm is your interface. Create each concrete class to implement your interface and work out your priorities accordingly.
Use like:
Algorithm algorithm = AlgorithmStrategy.getAlgorithm("Algorithmx");
Where "Algorithmx" is retrieved from your combo
Upvotes: 1