设计模式之组合模式

适用于:树结构。整体部分结构。

典型例子:文件夹和文件;JSON库的设计;Swing的容器和组件;


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


public class Test3 {

	public static void main(String[] args) {
		Component l1 = new Leaf("叶子1");
		Component l2 = new Leaf("叶子2");
		Component l3 = new Leaf("叶子3");
		
		Component c1 = new Composite("容器1");
		Component c2 = new Composite("容器2");
		
		// c1相当于根容器
		c1.add(l1);
		c1.add(c2);
		c2.add(l2);
		c2.add(l3);
		
		
		// 访问根容器。则可以访问到所有节点。 (整体)
		System.out.println("访问根容器:");
		c1.operation();
		
		// 也可以直接访问容器节点或叶子节点。 (部分)
		System.out.println("\n访问容器节点:");
		c2.operation();
		
		System.out.println("\n访问容器节点:");
		l1.operation();
	}

}

interface Component {
	void operation();
	
	// 集合操作方法。
	// 如果定义在这里,叫做透明的组合模式。如果在客户端需要面向抽象编程,需要使用该种模式。
	// 如果定义在容器节点,则叫做安全的组合模式。
	void add(Component c);
	void remove(Component c);
	Component getChild(int i);
}

// 叶子节点
class Leaf implements Component {

	private String name;
	
	public Leaf(String name) {
		this.name = name;
	}
	
	public void operation() {
		System.out.println(this.name);
	}
	
	// 集合操作方法。叶节点不支持这些操作。
	
	public void add(Component c) {
		throw new UnsupportedOperationException();
	}
	public Component getChild(int i) {
		throw new UnsupportedOperationException();
	}
	public void remove(Component c) {
		throw new UnsupportedOperationException();
	}
	
}

// 容器类
class Composite implements Component {

	private String name;
	
	public Composite(String name) {
		this.name = name;
	}
	
	// 持有抽象组件类集合。这样既可以包含叶节点,又可以继续包含容器节点。
	private List<Component> children = new ArrayList<Component>();
	
	// 递归遍历
	public void operation() {
		System.out.println(this.name);
		for (Component c : children) {
			c.operation();
		}
	}
	
	// 集合操作方法
	public void add(Component c) {
		children.add(c);
	}

	public Component getChild(int i) {
		return children.get(i);
	}

	public void remove(Component c) {
		children.remove(c);
	}
	
}

运行结果:

访问根容器:
容器1
叶子1
容器2
叶子2
叶子3

访问容器节点:
容器2
叶子2
叶子3

访问容器节点:
叶子1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值