组合模式

1、简介

组合模式(Composite Pattern ),也叫部分整体模式,适用于将一组相似的对象当做一个单一的对象。组合模式依据树形对象来组合对象,用来表示部分与整体的关系。


核心代码:树枝内部组合接口,并且含有List,里面存放Compoment

优点: 高层模块调用简单,节点自由增加。

缺点:树枝和子叶都是实现类,不是接口,违反了依赖倒置原则。


一个简答的例子就是传销,无限的发展下线,下线又可以发展下线。

2、使用

// emp
public class Employee {
	
	private String name;
	private String dept;
	private double salary;
	
	private List<Employee> oridationEmployee;
	
	public Employee(String name, String dept, double salary) {
		super();
		this.name = name;
		this.dept = dept;
		this.salary = salary;
		this.oridationEmployee = new ArrayList<Employee>();
	}
	
	public void add(Employee emp) {
		oridationEmployee.add(emp);
	}
	
	public void remove(Employee emp) {
		oridationEmployee.remove(emp);
	}
}

// 测试
	Employee CEO = new Employee("John", "CEO", 100000);
		
		Employee jams = new Employee("jams", "HEAD-SELLER", 10000);
		Employee gosling = new Employee("gosling", "HEAD-MARKING", 10000);
		
		Employee jery = new Employee("jery", "SELLER", 3000);
		Employee petter = new Employee("petter", "SELLER", 3000);
		
		Employee meeter = new Employee("meeter", "MARKING", 6000);
		Employee guval = new Employee("guval", "MARKING", 6000);
		
		CEO.add(jams);
		CEO.add(gosling);
		
		jams.add(jery);
		jams.add(petter);
		petter.add(meeter);
		petter.add(guval);
		
		System.out.println(CEO);
		printEmp(CEO.getOridationEmployee());
	}
	
	private static void printEmp(List<Employee> employees) {
		for(Employee emp: employees) {
			if(emp.getOridationEmployee().size() != 0) {
				printEmp(emp.getOridationEmployee());
			}else {
				System.out.println(emp);
			}
		}
	}

posted @ 2020-08-11 11:37  kungFuPander  阅读(88)  评论(0编辑  收藏  举报