欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

设计模式之组合模式——Java语言描述

程序员文章站 2022-07-02 17:02:48
组合模式又叫做部分整体模式,适用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次 ......

组合模式又叫做部分整体模式,适用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次

介绍

意图

将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性

优点

  1. 高层模块调用简单
  2. 节点*增加

缺点

在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口类,违反了依赖导致的原则

实现

创建一个employee类,使用该类作为组合模型。

创建employee类,该类带有employee对象的列表

import java.util.arraylist;
import java.util.list;
 
public class employee {
   private string name;
   private string dept;
   private int salary;
   private list<employee> subordinates;
 
   //构造函数
   public employee(string name,string dept, int sal) {
      this.name = name;
      this.dept = dept;
      this.salary = sal;
      subordinates = new arraylist<employee>();
   }
 
   public void add(employee e) {
      subordinates.add(e);
   }
 
   public void remove(employee e) {
      subordinates.remove(e);
   }
 
   public list<employee> getsubordinates(){
     return subordinates;
   }
 
   public string tostring(){
      return ("employee :[ name : "+ name 
      +", dept : "+ dept + ", salary :"
      + salary+" ]");
   }   
}

使用 employee 类来创建和打印员工的层次结构

public class compositepatterndemo {
   public static void main(string[] args) {
      employee ceo = new employee("john","ceo", 30000);
 
      employee headsales = new employee("robert","head sales", 20000);
 
      employee headmarketing = new employee("michel","head marketing", 20000);
 
      employee clerk1 = new employee("laura","marketing", 10000);
      employee clerk2 = new employee("bob","marketing", 10000);
 
      employee salesexecutive1 = new employee("richard","sales", 10000);
      employee salesexecutive2 = new employee("rob","sales", 10000);
 
      ceo.add(headsales);
      ceo.add(headmarketing);
 
      headsales.add(salesexecutive1);
      headsales.add(salesexecutive2);
 
      headmarketing.add(clerk1);
      headmarketing.add(clerk2);
 
      //打印该组织的所有员工
      system.out.println(ceo); 
      for (employee heademployee : ceo.getsubordinates()) {
         system.out.println(heademployee);
         for (employee employee : heademployee.getsubordinates()) {
            system.out.println(employee);
         }
      }        
   }
}

输出结果

employee :[ name : john, dept : ceo, salary :30000 ]
employee :[ name : robert, dept : head sales, salary :20000 ]
employee :[ name : richard, dept : sales, salary :10000 ]
employee :[ name : rob, dept : sales, salary :10000 ]
employee :[ name : michel, dept : head marketing, salary :20000 ]
employee :[ name : laura, dept : marketing, salary :10000 ]
employee :[ name : bob, dept : marketing, salary :10000 ]