组合模式(Composite)

UML类图:
在这里插入图片描述
组合模式的基本结构代码:
Component :是组合中的对象声明接口,在适当的情况下,实现所有类公有接口的默认行为。声明一个接口用于访问和管理Component子部件。
Leaf:在组合中表示叶子节点对象,叶子节点没有子节点。
Composite:定义分支节点行为,用来存储子部件,在Component接口中实现与 子部件有关的操作,如add和remove等

import java.util.ArrayList;
 
abstract class Component{
	protected String name;
	public Component(String name) {
		this.name=name;
	}
	public abstract void Add(Component component);
	public abstract void Remove(Component component);
	public abstract void Display(int d);
}
 
class Leaf extends Component{//叶子结点没有子节点
	public Leaf(String name) {
		super(name);
	}
	public void Add(Component component) {
		System.out.println("不能添加一个树叶");
	}
	public void Remove(Component component) {
		System.out.println("不能添加一个树叶");
	}
	public void Display(int d) {
		for(int i=0;i<d;i++)
			System.out.print(" ");
		System.out.println('-'+name);
	}
}
class Composite extends Component{
	private ArrayList<Component>components=new ArrayList<Component>();
	public Composite(String name) {
		super(name);
	}
	public void Add(Component component) {
		components.add(component);
	}
	public void Remove(Component component) {
		components.remove(component);
	}
	@Override
	public void Display(int d) {
		// TODO Auto-generated method stub
		for(int i=0;i<d;i++)
			System.out.print(" ");
		System.out.println('+'+name);
		for(Component component:components) {
			component.Display(d+2);
		}
	}
}
 
public  class Main{
	public static void main(String[] args){
		//生成树根,根上长出两个树叶LeafA和LeafB
				Composite composite=new Composite("root");
				composite.Add(new Leaf("LeafA"));
				composite.Add(new Leaf("LeafB"));
		//根上长出分支CompositeX,分支上也有两叶LeafAx和LeafBx
				Composite compositex=new Composite("CompositeX");
				compositex.Add(new Leaf("LeafAx"));
				compositex.Add(new Leaf("LeafBx"));
				composite.Add(compositex);
				
				Composite compositeY=new Composite("CompositeXY");
				compositeY.Add(new Leaf("LeafAxY"));
				compositeY.Add(new Leaf("LeafBxY"));
				compositex.Add(compositeY);
				
				composite.Add(new Leaf("LeafAxYc"));
				Leaf leaf=new Leaf("LeafAxYd");
				composite.Add(leaf);
				composite.Remove(leaf);
				composite.Display(1);
	}
}

       组合模式有时又叫做部分-整体模式(Part-Whole)。组合模式将对象组织到树结构中,可以用来描述整体与部分的关系。组合模式可以使客户端将单纯元素与复合元素同等看待。

抽象构件(Component)角色:这是一个抽象角色,它给参与组合的对象规定一个接口。这个角色给出共有接口及其默认行为。
树叶构件(Leaf)角色:代表参加组合的树叶对象。一个树叶对象没有下级子对象。
树枝构件(Composite)角色:代表参加组合的有子对象的对象,并给出树枝构件对象的行为。

使用组合模式的情况:
1、需求中是体现部分与整体层次的结构时
2、希望用户忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象时

优点:
1、定义了包含基本对象和组合对象的类层次结构
2、统一了组合对象和叶子对象
3、简化了客户端调用
4、更容易扩展

缺点:
很难限制组合中的组件类型

本质:
统一叶子对象和组合对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值