【设计模式】组合模式

1 简介

        组合模式(Composite Pattern)定义:将对象组合成树形结构,以表示“部分—整体”的层次结构。它使得客户对单个对象和复合对象的使用具有一致性。

2 代码

        (1)抽象构建(Component)

public abstract class Component {
	String info;
	public abstract void add(Component c);
	public abstract void remove(Component c);
	public abstract Component getChild(int i);
	public abstract void operation(int level);
}

        (2)叶子构件(Leaf)

public class Leaf extends Component{
	Leaf(String info){
		this.info=info;
	}
	
	@Override
	public void add(Component c) {
		throw new UnsupportedOperationException("Error:can't add a child to a leaf");
	}

	@Override
	public void remove(Component c) {
		throw new UnsupportedOperationException("Error:can't remove a child from a leaf");
	}

	@Override
	public Component getChild(int i) {
		throw new UnsupportedOperationException("Error:leaf has no child");
	}

	@Override
	public void operation(int level) {
		for(int i=0;i<level;i++)
			System.out.print("   ");
		System.out.println(info);
	}
}

        (3)容器构件(Composite)

import java.util.ArrayList;

public class Composite extends Component{
	private ArrayList<Component> list=new ArrayList<Component>();
	
	Composite(String info){
		this.info=info;
	}
	
	@Override
	public void add(Component c) {
		list.add(c);
	}

	@Override
	public void remove(Component c) {
		list.remove(c);
	}

	@Override
	public Component getChild(int i) {
		return list.get(i);
	}

	@Override
	public void operation(int level) {
		for(int i=0;i<level;i++)
			System.out.print("   ");
		System.out.println(info);
		for(Component c:list) {
			c.operation(level+1);
		}
	}
}

        (4) 客户端(Client)

public class Client {

	public static void main(String[] args) {
		Component University=new Composite("清华大学");
		
		Leaf ministry=new Leaf("行政部");
		Composite computer=new Composite("计算机学院");
		Composite management=new Composite("管理学院");
		University.add(ministry);
		University.add(computer);
		University.add(management);
		
		Leaf softwareEngineering=new Leaf("软件工程");
		Leaf computerTechnology=new Leaf("计算机技术");
		computer.add(softwareEngineering);
		computer.add(computerTechnology);
		
		Leaf informationManagement=new Leaf("信息管理");
		Leaf businessAdministration=new Leaf("工商管理");
		management.add(informationManagement);
		management.add(businessAdministration);
		
		University.operation(0);
	}
}

        运行结果:

清华大学
   行政部
   计算机学院
      软件工程
      计算机技术
   管理学院
      信息管理
      工商管理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

little_fat_sheep

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值