组合模式

文档查阅说明:

Tongkey

yiibai

runoob

大话设计模式

定义:将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性

使用场景:

● Component抽象构件角色

定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性,比如我们例子中的getInfo就封装到了抽象类中。

● Leaf叶子构件

叶子对象,其下再也没有其他的分支,也就是遍历的最小单位。

● Composite树枝构件

树枝对象,它的作用是组合树枝节点和叶子节点形成一个树形结构

public abstract class Component {

	private String name;

	public Component(String name) {
		super();
		this.name = name;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public abstract void add(Component component);
	public abstract void remove(Component component);
	public abstract void display(int depth);
	
}
public class Composite extends Component {
	
	public Composite(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

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

	@Override
	public void add(Component component) {
		children.add(component);
	}

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

	@Override
	public void display(int depth) {
		String tmp = "-";
		for(int i =0; i< depth; i++) {
			System.out.print("-");
		}
		System.out.println(this.getName());
		
		for(Component component:children){
			component.display(depth + 2);
		}
	}

}
public class Leaf extends Component {

	public Leaf(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void add(Component component) {
		// TODO Auto-generated method stub
		System.out.println("cannot add a leaf");
	}

	@Override
	public void remove(Component component) {
		// TODO Auto-generated method stub
		System.out.println("cannot remove from a leaf");
	}

	@Override
	public void display(int depth) {
		// TODO Auto-generated method stub
		String tmp = "-";
		for(int i =0; i< depth; i++) {
			System.out.print("-");
		}
		System.out.println(this.getName());
	}

}
public class Test {
	public static void main(String[] args) {
		Composite root = new Composite("root");
		root.add(new Leaf("A"));
		root.add(new Leaf("B"));
		
		Composite comp = new Composite("X");
		comp.add(new Leaf("X.A"));
		comp.add(new Leaf("X.B"));
		
		root.add(comp);
		
		Composite comp2 = new Composite("Y");
		comp2.add(new Leaf("Y.A"));
		
		Composite comp3 = new Composite("Z");
		comp3.add(new Leaf("Z.A"));
		comp3.add(new Leaf("Z.B"));
		
		comp2.add(new Leaf("Y.B"));
		comp2.add(comp3);
		
		root.add(comp2);
		
		root.add(new Leaf("C"));
		
		root.display(1);
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值