vendredi 19 octobre 2018

Composite Design Pattern, let child (composite) know who its parent is

So I've been stuck at this for awhile now. Basically I want to let the composite component know its parent. When I tried to access the parent object in parameter, it gives me null when I try to log it, but if I try to print out the object's name, it doesn't throw me errors. Sorry for the poorly formatted code and every help will be appreciated, please let me know if there is anything I could add if the question is unclear or vague. Thanks!

This is the employee class

public class Employee {

   protected String name;
   protected Employee parent;

   public Employee() {
    this.parent = null;
    this.name = "name not set";
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
    this.name = name;
   }

   public Employee getParent() {
       return parent;
   }

   public void setParent(Employee parent) {
       this.parent = parent;
      }
   }

This is developer class

   public class Developer extends Employee {
   protected ArrayList<Employee> staffList;

   public Developer() {
       super();
       this.staffList = new ArrayList<Employee>();
   }

    public void add(Employee e) throws Exception {
       System.out.println(e.getParent()); //prints null even though the parameter has parent
       if (e.getParent() instanceof Developer) {
           throw new Exception("You cannot add staff when your lead is a dev");
       } else if (e instanceof Manager) {
           throw new Exception("You cannot add manager as your staff bcs u r a dev");
       }

       e.setParent(this);
       this.staffList.add(e);
   }

   public void printData() {
       for(Employee e : staffList) {
           System.out.println(e.name);
       }
   }

}

This is Manager class

public class Manager extends Employee {
protected ArrayList<Employee> staffList;

public Manager() {
    // TODO Auto-generated constructor stub
    super();
    this.staffList = new ArrayList<Employee>();
}    

 public void add(Employee e) {
     e.setParent(this);
     this.staffList.add(e);
 }

 public void printData() {
        for(Employee e : staffList) {
            System.out.println(e.name);
        }
     }
 }

Aucun commentaire:

Enregistrer un commentaire