java之组合模式

组合模式

定义

组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。

示例

员工类

public class Employee {

	private String name;
	private String dept;
	private List<Employee> employees = null;
	
	public Employee(String name,String dept) {
		this.name = name;
		this.dept = dept;
		employees = new ArrayList<Employee>();
	}
	
	public void addEmployee(Employee e){
		this.employees.add(e);
	}
	
	public void delEmployee(Employee e){
		this.employees.remove(e);
	}
	
	public List<Employee> getEmployee(){
		return employees;
	}
	
	@Override
	public String toString() {
		return "{\"name\":\""+name+"\",\"dept\":\""+dept+"\",\"sub\":"+employees+"}";
	}
}

测试类

public class CompositeTest {

	public static void main(String[] args) {
		Employee employee = new Employee("huzd", "CEO");
		
		Employee employeeSales = new Employee("huzdSales1", "Sales");
		Employee employeeMarketing = new Employee("huzdSales2", "Marketing");
		
		Employee employeeTester1 = new Employee("huzdTester1", "Tester");
		Employee employeeTester2 = new Employee("huzdTester2", "Tester");
		
		Employee employeeProgrammer1 = new Employee("huzdProgrammer1", "Programmer");
		Employee employeeProgrammer2 = new Employee("huzdProgrammer2", "Programmer");
		
		employee.addEmployee(employeeSales);
		employee.addEmployee(employeeMarketing);
		
		employeeSales.addEmployee(employeeTester1);
		employeeSales.addEmployee(employeeTester2);
		
		employeeMarketing.addEmployee(employeeProgrammer1);
		employeeMarketing.addEmployee(employeeProgrammer2);
		
		System.out.println(employee);
	}
}

分析

  1. 将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
  2. 优点 1、高层模块调用简单。 2、节点自由增加。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值