將對象組合成樹型結(jié)構(gòu)以表示“整體-部分”的層次結(jié)構(gòu),使得用戶對單個對象和組合對象的使用具有一致性。
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("");
}
}
/** 抽象構(gòu)件角色類 */
abstract class Component {
protected void addChild(Component child) {
throw new UnsupportedOperationException();
}
protected void removeChild(Component child) {
throw new UnsupportedOperationException();
}
/** 輸出對象的自身結(jié)構(gòu) */
protected abstract void printStruct(String preStr);
}
/** 樹枝構(gòu)件角色類 */
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);
}
}
/** 葉子構(gòu)件角色類 */
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);
}
}