日拱一卒(三十七)

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

       白话:典型的模型就是“文件和文件夹”,文件和文件夹都存在拷贝的功能,文件可以单独存在,也可以组合在文件夹中,但他们的拷贝行为却是一致的。

       角色:

(1)leaf:叶子,单独存在,不存在组合关系;

(2)Composite:枝节点,组合叶子或者子枝节点;

(3)Component:叶子和枝节点共同的基类(接口),使枝节点和叶子拥有相同的行为。

日拱一卒(三十七)_第1张图片

:因为文件(叶子)和文件夹(枝节点)存在相同的行为,因此通常拥有共同的基类(接口)Componet;

使用场景:当对象既可以单独存在,又可以被组合到另一个类,而这两种方式表象的行为又一致,则可以使用组合模式。比如文件和文件夹拥有相同的拷贝功能;公司中总公司的人事部门和分公司的人事部门功能相差无几。

实例:以文件和文件夹说明

interface IAction {
	public void copy(String distPath);
}

class File implements IAction {
	private String file;

	public File(String file) {
		super();
		this.file = file;
	}

	@Override
	public void copy(String distPath) {
		System.out.print("copy the file:" + file + " to " + distPath);
	}
}

class Folder implements IAction {
	private List<File> files = new ArrayList<File>();
	private String folder;

	public Folder(String folder) {
		super();
		this.folder = folder;
	}

	@Override
	public void copy(String distPath) {
		System.out.print("copy the folder:" + folder + " to " + distPath);
		for (File file : files) {
			file.copy(distPath);
		}
	}

	public void addFile(File file) {
		files.add(file);
	}

	public void remoeFile(File file) {
		files.remove(file);
	}
}

测试类:

public class CompositTest {
	public static void main(String[] args) {
		File file = new File("松岛枫");
		File file2 = new File("小泽玛利亚");
		Folder folder = new Folder("爱情动作片");
		folder.addFile(file);
		folder.addFile(file2);
		folder.copy("C://毛邓三");
		file.copy("U盘");
	}
}

可以看到文件File独立存在还是组合到Folder中都是相同的copy行为。

你可能感兴趣的:(android)