組合模式

將對象組合成樹型結(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);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容