將物件當作一個元件,將很多元件組合成樹狀結構,有人也稱為部分整理模式(part-whole pattern)。
組合模式定義
單個物件與組合的物件都有一致性
組合模式使用情況
- 有物件需要表達複數的狀況
組合模式UML圖
組合模式範例
我們建立員工資料,利用組合模式建立多筆的員工資料
/** * name: Employee.java * description : 員工個人資料 * Created by bryant on 2017/1/25. */ public class Employee { public Employee(String name, String dept, BigDecimal salary){ this.name = name ; this.dept = dept ; this.salary = salary; } private String no; //員工姓名 private String name ; //薪水 private BigDecimal salary ; //部門 private String dept ; //取得員工姓名 public String getName() { return name; } //設定員工姓名 public void setName(String name) { this.name = name; } //取得員工薪水 public BigDecimal getSalary() { return salary; } //設定員工薪水 public void setSalary(BigDecimal salary) { this.salary = salary; } //取得部門 public String getDept() { return dept; } //設定部門 public void setDept(String dept) { this.dept = dept; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } @Override public int hashCode() { return Integer.valueOf(this.no); } @Override public String toString() { StringBuilder sb = new StringBuilder() ; sb.append("") ; sb.append(""+no+"") ; sb.append(""+name+"") ; sb.append(""+dept+"") ; sb.append(""+salary+"") ; sb.append(""+"\r\n") ; return sb.toString(); } }
/** * name: EmployeeComposite.java * description : 員工集合 * Created by bryant on 2017/1/25. */ public class EmployeeComposite { private List list = new ArrayList() ; public List getEmployees(){ return list; } public void addEmployee(Employee employee){ list.add(employee); } public void remove(Employee employee){ list.remove(employee); } @Override public String toString() { StringBuilder sb = new StringBuilder() ; for (Employee e: list){ sb.append(e.toString()); } return sb.toString() ; } }
/** * name: EmployeeCompositeDemo.java * description : 員工集合DEMO * Created by bryant on 2017/1/25. */ public class EmployeeCompositeDemo { public static void main(String[] args){ Employee worker01 = new Employee("Jacker", "Worker",new BigDecimal("31000")) ; Employee worker02= new Employee("Mary", "Worker",new BigDecimal("31000")) ; Employee manager = new Employee("Bob","Manager", new BigDecimal("51000")) ; EmployeeComposite employeeComposite = new EmployeeComposite() ; employeeComposite.addEmployee(worker01); employeeComposite.addEmployee(worker02); employeeComposite.addEmployee(manager); System.out.println(employeeComposite.toString()); } }
留言
張貼留言