• 设计模式(组合模式)


    组合模式是为了解决业务中“局部-整体”的关系,这里的局部整体互相嵌套,且具备相同的处理接口。

    典型的角色是两个:

    • component:包含自身抽象列表的类,下例中为Employee;
    • composite:各个组成部分对外暴露的处理接口,下例中为toString,为单独抽象;

    代码如下:

    • Employee
    package com.example;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class Employee {
    
        private String name;
        private String deptname;
        private List<Employee> subs;
        
        public Employee(String name, String deptname){
            this.name = name;
            this.deptname = deptname;
            subs = new ArrayList<Employee>();        
        }
    
        public void add(Employee e) {
            subs.add(e);
        }
    
        public void remove(Employee e) {
            for (Iterator<Employee> it = subs.iterator(); it.hasNext();) {
                if (((Employee) it.next()).name == e.name) {
                    it.remove();
                }
            }
        }
        
        //这里的toString,等价于于composite方法
        public String toString() {
            return ("Employee :[ Name : " + name + ", dept : " + deptname + " ]");
        }
    
        public List<Employee> getSubs() {
            return subs;
        }
    
    }
    • App 测试类
    public class App {
    
        public static void main(String[] args) {
            Employee e1 = new Employee("fredric", "dept1");
            Employee e2 = new Employee("sinny", "dept2");
            Employee e3 = new Employee("baobao", "dept2");
            e1.add(e2);
            e1.add(e3);
            for(Employee emp:e1.getSubs()){
                System.out.println(emp);
            }
            e1.remove(e2);
            for(Employee emp:e1.getSubs()){
                System.out.println(emp);
            }        
        }
    }
  • 相关阅读:
    《病理学》读书笔记
    《药理学》读书笔记
    《人格心理学》读书笔记
    《普通心理学》读书笔记
    UI进阶 跳转系统设置相关界面的方法
    安装cocoapods
    CocoaPods 添加第三方库报错
    Objective-c setObject:forKey:和setValue:forKey:的区别
    解析稍微复杂一点的数据
    获取当前屏幕显示的viewcontroller
  • 原文地址:https://www.cnblogs.com/Fredric-2013/p/4571991.html
Copyright © 2020-2023  润新知