java - Design pattern for prioritization of graph nodes -
problem solve: give priority (int value) nodes of graph. there dag class attribute graph (of type directedgraph jgrapht library). moreover, there must different algorithms assign priorities, , must possible add new algorithms in future without modifying existing code. dag created first, , user have possibility select algorithm use (using combobox in gui). user must have possibility change algorithm @ moment.
approach 1: develop interface (algorithm) algorithms, , make algorithms implement interface. in dag class, add new attribute:
algorithm myalgo;
each time user selects different algorithm on gui, instantiate algorithm:
myalgo = new algorithmnumberx;
approach 2: write prioritization task independently (not attribute of dag), use static method prioritize nodes of dag, sending dag argument , returning modified dag.
which advantages has each approach?
i go option 1 (as have). describing strategy pattern (a combination of both options actually). problematic thing may have approach getting class names enter combo box. need add object creates instance you. if new algorithmx need add such statement each algorithm add against requirements stated.
public class algorithmstrategy { public static final algorithm getalgorithm(string classname) { algorithm algorithm = null; string name = "<package algorithms in>." + classname; try { algorithm = (algorithm)class.forname(name).newinstance(); } catch (instantiationexception | illegalaccessexception | classnotfoundexception e) { e.printstacktrace(); } return algorithm; } }
in example algorithm interface. create each concrete class implement interface , work out priorities accordingly.
use like:
algorithm algorithm = algorithmstrategy.getalgorithm("algorithmx");
where "algorithmx" retrieved combo
Comments
Post a Comment