设计模式java——组合模式

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

组合模式Demo:

/**
 * 2018年4月2日下午9:09:51
 */
package com.Designpattern;

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

/**
 * @author xinwenfeng
 *
 */
public class TestComposite {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MyFolder root = new MyFolder("根目录");
		MyFolder folder1 = new MyFolder("视频");
		MyFile file1_1 = new MyFile("吸血鬼日记第一季第一集.avi");
		MyFile file1_2 = new MyFile("上上下下左右左右BABA.mp4");
		MyFolder folder2 = new MyFolder("游戏");
		MyFile file2_1 = new MyFile("使命召唤4");
		MyFile file2_2 = new MyFile("大菠萝3");
		MyFolder folder2_2 = new MyFolder("经典游戏");
		MyFile file2_2_1 = new MyFile("魂斗罗");
		MyFile file2_2_2 = new MyFile("超级玛丽");
		MyFile file2_2_3 = new MyFile("冒险岛");
		
		folder2_2.add(file2_2_1);//这让我想起了JFrame
		folder2_2.add(file2_2_2);
		folder2_2.add(file2_2_3);
		
		folder1.add(file1_1);
		folder1.add(file1_2);
		
		folder2.add(file2_1);
		folder2.add(file2_2);
		folder2.add(folder2_2);
		
		root.add(folder1);
		root.add(folder2);
		
		root.show(0);
		
		folder2.remove(folder2_2);
		
		root.show(0);
	}
}
interface Component{
	public void add(Component c);
	public void remove(Component c);
	public void show(int index);
	
	default public String getPrefix(int k) {
		String s = "";
		for(int i=0;i children = new ArrayList<>();//保存子目录

	public MyFolder(String name) {
		this.name = name;
	}
	
	@Override
	public void add(Component c) {
		children.add(c);
	}

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

	@Override
	public void show(int index) {
		System.out.println(getPrefix(index)+"[+]"+name);//展示文件夹
		children.forEach(c -> {c.show(index+1);});//展示子目录
	}
	
}
class MyFile implements Component{

	private String name;
	
	public MyFile(String name) {
		this.name = name;
	}
	
	@Override
	public void add(Component c) {
		System.out.println("error");
	}

	@Override
	public void remove(Component c) {
		System.out.println("error");
	}

	@Override
	public void show(int index) {
		System.out.println(getPrefix(index)+"[-]"+name);//展示文件
	}
	
}

结果:

设计模式java——组合模式_第1张图片

你可能感兴趣的:(设计模式Demo)