I am new to designing softwares, and I am trying to build a Tree like struct.
I have an empty interface like this:
interface Node{
}
Two classes NodeA
and NodeB
implement this interface, and both have some specific attributes. Except that these are Nodes, they dont have anything common in them.
class A implements Node {
public String a;
public A(String a){
this.a = a;
}
}
class B implements Node {
public int a = 5;
public String z = "xyz";
public B(int a,String z){
this.a = a;
this.z = z;
}
}
I have a a class Parse
that creates instances of the above classes , depending on certain conditions.
class Parse {
List<Boolean> l;
private static int i=0;
Parse(List<Boolean> l){
this.l = l;
}
private Node parseA() {
return new A(/* param */); // Assume some parameters here
}
private Node parseB() {
return new B(/* param */); // Assume some parameters here
}
private boolean getNextState(){
return l.get(i++);
}
public Node parse(){
boolean x = getNextState();
if(x){
return parseA();
}
else{
return parseB();
}
}
}
Driver class:
public class Test {
public static void main(String[] args) {
List<Boolean> l = Arrays.asList(true,false); // so on...
Parse p = new Parse(l);
Node b = p.parse(); // not sure if its NodeA or NodeB
}
}
After building the tree, i am planning to use visitor pattern to retrieve some attributes and do some operations.
So at last, when i get a
Node b
, i want to access its attributes (ofNodeA
orNodeB
), which i know cant be done as Polymorphism doesnt work that way.
I think that using instanceof
ladder and type-casting arent proper solutions to it.
Sorry for this silly problem, but being new to designing, i aint getting what to do next.
How shall one solve this design problem? can anyone share a small design structure for this, assuming that this structure will grow bigger and have ample of different nodes. [may be Java Generics
help here]
Note: chaning above design is fine,but if possible, a small sample code is appreciated.
Aucun commentaire:
Enregistrer un commentaire