10组合模式

组合模式

<设计模式其实很简单>笔记


①定义:
将对象组成树形结构以表示“部分-整体”的层次结构。
组合模式使得用户对单个对象和组合对象的使用具有一致性。
②理解:
树和子树,即整体与部分。在树形结构中,部分和整体有着类似或相同的结构,所以可以将部分和

整体一致对待


③代码:

//树中分支节点与叶子节点的抽象父类
public abstract class Component{
	//组件名称
	protected String componentName;
	//构造方法
	public Component(String componentName){
		this.componentName = componentName;
	}
	//增加分支/叶子节点的方法
	public abstract void Add(Component component);
	//移除分支/叶子节点的方法
	public abstract void Remove(Component component);
	//按照深度显示树形结构的方法
	public abstract void Show(int depth);
}
//分支节点的类
public class Composite extends Component{
	private List<Component> childrenList = new ArrayList<Component>();
	public Composite(String componentName){
		super(componentName);
	}
	//增加子节点
	@Override
	public void Add(Component component){
		childrenList.add(component);
	}
	//移除子节点
	@Override
	public void Remove(Component component){
		childrenList.remove(component);
	}
	//展示结构
	@Override
	public void Show(int depth){
		for(int i = 0 ; i < depth ; i++){
			System.out.print("+");
		}
		System.out.print(componentName + "\n");
		for(int i = 0 ; i < childrenList,size() ; i++){
			(Component)childrenList.get(i).Show(depth+2);
		}
	}
}
//树叶节点
public class Leaf extends Component{
	//构造函数
	public Leaf(String componentName){
		super(componentName);
	}
	//增加子节点
	@Override
	public void Add(Component component){
		System.out.println("叶子节点无法增加新的子节点!");
	}
	//移除子节点
	@Override
	public void Remove(Component component){
		System.out.println("叶子节点无法移除节点!");
	}
	//展示结构
	@Override
	public void Show(int depth){
		for(int i = 0 ; i < depth ; i ++){
			System.out.println("+");
		}
				System.out.println( componentName + "\n");
	}
}

④适用的地方:
当开发的代码需要表示部分和整体的结构时
当希望用户忽略组合对象和单个对象之间的不同时
⑤优点:
组合模式可以优化处理递归或分级数据结构。分级数据结构如计算机的文件系统。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值