Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I am having issues rewriting the following code as a builder design pattern: MAIN: public class Main { public static void main(String[] args) { /*
I am having issues rewriting the following code as a builder design pattern: MAIN: public class Main { public static void main(String[] args) { /* (for instance like one used on genealogy sites). For the sake of simplicity, assume an individual can have at most two children. If an individual has 1-2 children, they are considered a "tree". If an individual does not have children, they are considered a "person". With that in mind, let's populate a family tree with some data. */ Person p1 = new Person(1); Person p2 = new Person(2); Person p3 = new Person(3); Person p4 = new Person(4); Tree t1 = new Tree(p1, 1); Tree t2 = new Tree(p2, p3, 2); Tree t3 = new Tree(t1, p4, 3); Tree t4 = new Tree(t3, t2, 4); t4.print(); } } CLASSES: public class Person { String name; public Person(int num) { name = "person" + num; } public void print() { System.out.println(name); } } public class Tree { private String name; private Tree tree1; private Tree tree2; private Person person1; private Person person2; public Tree(Person p1, int num) { tree1 = null; tree2 = null; person1 = p1; person2 = null; name = "tree" + num; } public Tree(Tree t1, int num) { tree1 = t1; tree2 = null; person1 = null; person2 = null; name = "tree" + num; } public Tree(Tree t1, Tree t2, int num){ tree1 = t1; tree2 = t2; person1 = null; person2 = null; name = "tree" + num; } public Tree(Tree t1, Person p2, int num){ tree1 = t1; tree2 = null; person1 = null; person2 = p2; name = "tree" + num; } public Tree(Person p1, Person p2, int num){ tree1 = null; tree2 = null; person1 = p1; person2 = p2; name = "tree" + num; } public void print() { System.out.println(name); if (tree1 != null) { tree1.print(); } if (tree2 != null) { tree2.print(); } if (person1 != null) { person1.print(); } if (person2 != null) { person2.print(); } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
To rewrite the code using the builder design pattern you can follow these steps Create a builder class for the Tree object that will handle the constr...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started