将对象组合成树型结构以表示“整体-部分”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
package com.strife.pattern.composite;
import java.util.ArrayList;
import java.util.List;
/**
* @author mengzhenghao
* @date 2022/5/30
*/
public class Code01{
public static void main(String[] args) {
Component component = new Composite("服装");
Component manCoat = new Composite("男装");
manCoat.addChild(new Leaf("上衣"));
manCoat.addChild(new Leaf("下衣"));
component.addChild(manCoat);
Component womanCoat = new Composite("女装");
womanCoat.addChild(new Leaf("裙子"));
component.addChild(womanCoat);
component.addChild(new Composite("鞋子"));
component.printStruct("");
}
}
/** 抽象构件角色类 */
abstract class Component {
protected void addChild(Component child) {
throw new UnsupportedOperationException();
}
protected void removeChild(Component child) {
throw new UnsupportedOperationException();
}
/** 输出对象的自身结构 */
protected abstract void printStruct(String preStr);
}
/** 树枝构件角色类 */
class Composite extends Component {
private List<Component> childComponents = new ArrayList<>();
private String name;
public Composite(String name) {
this.name = name;
}
@Override
protected void printStruct(String preStr) {
System.out.println(preStr + name);
StringBuilder preStrBuilder = new StringBuilder(preStr);
preStrBuilder.append("\t");
for (Component component : childComponents) {
component.printStruct(preStrBuilder.toString());
}
preStr = preStrBuilder.toString();
}
@Override
protected void addChild(Component child) {
childComponents.add(child);
}
@Override
protected void removeChild(Component child) {
childComponents.remove(child);
}
}
/** 叶子构件角色类 */
class Leaf extends Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
protected void printStruct(String preStr) {
System.out.println(preStr + name);
}
}