组合模式--用于树形结构的场景

Component.java

package com.godv.composite;

//叶子节点和根节点的抽象类
public abstract class Component {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	// 提供一个add方法用来构建树
	public void add(Component component) {
		throw new UnsupportedOperationException();
	}

	public void remove(Component component) {
		throw new UnsupportedOperationException();
	}

	// 打印方法 类似于叶子节点和根节点都需要重写的方法
	public abstract void print();

}

University.java     根节点

package com.godv.composite;

import java.util.ArrayList;
import java.util.List;

public class University extends Component {

	private List<Component> mList = new ArrayList<>();

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return super.getName();
	}

	@Override
	public void setName(String name) {
		// TODO Auto-generated method stub
		super.setName(name);
	}

	@Override
	public void add(Component component) {
		// TODO Auto-generated method stub
		mList.add(component);
	}

	@Override
	public void remove(Component component) {
		// TODO Auto-generated method stub
		mList.remove(component);
	}

	@Override
	public void print() {
		// TODO Auto-generated method stub
		System.out.println(getName());
		for (Component component : mList) {
			component.print();
		}
	}

}

Department.java    叶子节点   叶子节点不需要再有子节点

package com.godv.composite;

public class Department extends Component{
	
	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return super.getName();
	}

	@Override
	public void setName(String name) {
		// TODO Auto-generated method stub
		super.setName(name);
	}

	@Override
	public void print() {
		// TODO Auto-generated method stub
		System.out.println(getName());
	}

}

Client.java

package com.godv.composite;

public class Client {
	public static void main(String[] args) {
		Component university = new University();
		university.setName("清华大学");
		
		Component university2 = new University();
		university2.setName("计算机学院");
		
		Department department = new Department();
		department.setName("软件工程");
		
		Department department2 = new Department();
		department2.setName("通信工程");
		
		university.add(university2);
		
		university2.add(department);
		university2.add(department2);
		
		university.print();
	}

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值