• 组合模式(Composite Pattern)


    组合模式:把一组相似的对象当成一个单一的对象,依据树形结构来组合对象,用来表示部分和整体层次。

    举一个管理公司员工的例子:

    public class Employee {
        private String name;
        private String dept;
        private double salary;
        private List<Employee> sub;
    
        public Employee(String n,String d,int s) {
            name = n;
            dept = d;
            salary = s;
            sub = new ArrayList<Employee>();  
        }
        public void add(Employee e) {
            sub.add(e);
        }
        public void remove(Emplyee e) {
            sub.remove(e);
        }
    public List<Employee> getSub() {
        return sub;
      }
    public String toString() {
            return "Name:" + name + "dept:" + depr + "salary:" + salary;
       }
    }

    测试代码:

    Employee CEO = new Employee("A0","CEO",30000);
    
    Employee headMarketing = new Employee("B0","Head Marketing", 20000);
    Employee clerk1 = new Employee("C0","Marketing",10000);
    Employee clerk2 = new Employee("C1","Marketing",10000);
    
    
    Employee headSales = new Employee("B1","Head Sales",20000);
    Employee sale1 = new Employee("C2","Marketing",10000);
    Employee sale2 = new Employee("C3","Marketing",10000);
    
    CEO.add(headMarking);    //CEO管理headMarking
    CEO.add(headSales);       // CEO管理headSales
    
    headMarking.add(clerk1);   //headMarking管理两个人
    headMarking.add(clerk2);
    
    headSales.add(sale1);    //headSales管理两个人
    headSales.add(sale2);
    
    //打印所有员工
    System.out.println(CEO);
    for(Employee e1 : CEO.getSub()) {
        System.out.println(e1);
        for(Employee e2: e1.getSub()) {
            System.out.println(e2);
        }
    }

     组合模式适合处理树形结构问题,如树形菜单,文件夹文件管理。

  • 相关阅读:
    收录
    查看表结构(数据字段说明等)
    JS 转换日期UTC类型
    Vue项目搭建
    win10 解决端口被占用
    mybatis 生成代码配置 mybatis-generator:generate 的使用详解
    mybatis-generator:generate 生成代码配置踩坑详解
    Spring boot 集成 Druid 数据源
    Spring Boot跨域解决方案
    Sublime Text 实用方法
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5522931.html
Copyright © 2020-2023  润新知