【设计模式】结构型05组合模式(Composite Pattern)

组合模式(Composite Pattern)

意图:将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

主要解决:它在我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。

何时使用:1、您想表示对象的部分-整体层次结构(树形结构)。2、您希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。

如何解决:树枝和叶子实现统一接口,树枝内部组合该接口。

关键代码:树枝内部组合该接口,并且含有内部属性 List,里面放 Component。



类图:这里从类图可以很好的理解,恩,复习的时候再画用于深化~

代码:这里我使用了四人帮《java设计模式》一书中的经典例子做演示,简化了一些内容,以便理解其核心-结构


1、组合接口

package com.pat.composite;
/**
 * 组合类接口,普通叶子和含有很多叶子的枝干都实现本接口
 * @author ZX
 *
 */
public interface Composite {
	void operation();
	void add(Composite leaf);
	void remove();

}

2、单独的实现类-叶子、

package com.pat.composite;
/**
 * 绿色的树叶
 * @author ZX
 *
 */
public class GreenLeaf implements Composite{
	@Override
	public void operation() {
		System.out.println("摘一片绿叶");
		
	}
	@Override
	public void add(Composite leaf) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void remove() {
		// TODO Auto-generated method stub
		
	}

}
package com.pat.composite;
/**
 * 黄色的树叶
 * @author ZX
 */
public class YellowLeaf implements Composite{
	@Override
	public void operation() {
		System.out.println("摘一片黄叶");
	}

	@Override
	public void add(Composite leaf) {
	}
	@Override
	public void remove() {
	}
}

3、枝干实现类-枝干上有许多叶子:

package com.pat.composite;

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

/**
 * 树枝,上面有很多树叶
 * @author ZX
 *
 */
public class Branch implements Composite{
	//树枝上所有的叶子集合
	List<Composite> leafs = new ArrayList<>();
	@Override
	public void operation() {
		operateAll();	
	}
	@Override
	public void add(Composite leaf) {
	}
	@Override
	public void remove() {
	}
	public void operateAll() {
		for(Composite leaf:leafs) {
			leaf.operation();
		}
		
	}
	//后早方法
	public Branch() {
		//这里我简单添加了一些树叶类,未使用传入参数,核心不在于此
		leafs.add(new GreenLeaf());
		leafs.add(new GreenLeaf());
		leafs.add(new GreenLeaf());
		leafs.add(new YellowLeaf());
		leafs.add(new YellowLeaf());
		leafs.add(new YellowLeaf());
	}

}

4、测试类:

package com.pat.composite;

public class Test {
	public static void main(String[] args) {
		System.out.println("===========================");
		Composite green = new GreenLeaf();
		green.operation();
		System.out.println("===========================");
		Composite yellow = new YellowLeaf();
		yellow.operation();
		System.out.println("===========================");
		Composite branch = new Branch();
		branch.operation();
		System.out.println("===========================");
	}
}
5、结果:
===========================
摘一片绿叶
===========================
摘一片黄叶
===========================
摘一片绿叶
摘一片绿叶
摘一片绿叶
摘一片黄叶
摘一片黄叶
摘一片黄叶
===========================


猜你喜欢

转载自blog.csdn.net/the_fool_/article/details/80367980