结构模式之组合模式

组合模式是专门用来解决树形结构的问题的:

package com.djk.design.struct.compose;

public interface Component
{
	void add(Component component);
	
	void reomve(Component component);
	
	void action();
}

package com.djk.design.struct.compose;

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

public class Compose implements Component
{
	private String name;
	
	public Compose(String name) {
		super();
		this.name = name;
	}

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

	@Override
	public void action()
	{
		System.out.println("Compose========"+name);
		for (Component component : list)
		{
			if (null != component)
			{
				component.action();
			}
		}
	}

	@Override
	public void add(Component component) 
	{
		
		if (null == component)
		{
			return ;
		}
		if (!list.contains(component))
		{
			list.add(component);
		}
	}

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

}
package com.djk.design.struct.compose;

public class Leaf implements Component
{
	
	private String name;

	public Leaf(String name) {
		super();
		this.name = name;
	}

	@Override
	public void action() 
	{
		System.out.println(name);
	}

	@Override
	public void add(Component component) 
	{
		throw new RuntimeException("leaf can not add component");
	}

	@Override
	public void reomve(Component component) 
	{
		
		throw new RuntimeException("leaf can not remove component");
	}

}
package com.djk.design.struct.compose;

public class Client 
{
	public static void main(String[] args) 
	{
		Component breakfast  = new Compose("早餐");
		Component  food = new Compose("饭");
		food.add(new Leaf("大米饭"));
		food.add(new Leaf("粥"));
		breakfast.add(food);
		Component water = new Compose("饮料");
		water.add(new Leaf("白开水"));
		water.add(new Leaf("牛奶"));
		breakfast.add(water);
		breakfast.action();
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值