lundi 8 octobre 2018

Java Software design: Making a generic tree - printing library

I am in the process of coding a project for the tree data structure - specifically, the main functionality it will provide is to display a given tree in different ways (different layouts on the JFrame canvas screen). For sake of simplicity, I am assuming that the tree which needs to be printed will always be a binary tree.

The algorithm for calculating the layout needs me to do an inorder/preorder/postorder traversal of the tree. In my project, I am going to write methods similar to the following:

class MyBinaryTreePrinterProject{

public void inOrderTraversal(Object root){
    // do inorder traversal
}

public void preOrderTraversal(Object root){
    // do preorder traversal
}

public void postOrderTraversal(Object root){
    // do postorder traversal
}
}

The root node is passed as an object, because the binary tree might be defined in some other external project with its own custom class definition. For example, following are two projects having their own class definitions of representing a binary tree:

// Tree definition in some unrelated Project A
class ProjectATreeNode{
public ProjectATreeNode left;
public ProjectATreeNode right;
...
}

// Tree definition in some unrelated Project B
class ProjectBTreeNode{
public ProjectBTreeNode leftChild;
public ProjectBTreeNode rightChild;
...
}

How will the methods in class MyBinaryTreePrinterProject know about the structure of the binary tree provided? For example, binary tree from Project A has a field called 'left' to access the left child, while Project B names it 'leftChild'. My initial thought was to use Java Reflection (along with requesting the user to provide the field names for accessing left/right children), but I am not sure whether this is the right way to go.

Does a better design exist?





Aucun commentaire:

Enregistrer un commentaire