一個簡單的組合模式練習題

組合模式

練習

請用組合設計模式編寫程序,打印輸出圖 1 的窗口,窗口組件的樹結構如圖 2 所示,打印輸出示例參考圖 3。
在這裏插入圖片描述

什麼是組合模式

引用維基百科:在軟件工程中,組合模式是一種分區設計模式。組合模式描述了一組對象,這些對象被視爲同一類型對象的單個實例。組合的目的是將對象“組合”成樹形結構以表示部分-整體層次結構。實施這模式可以使客戶統一對待各個對象和構圖;

do

在上述題目中,根據圖2的樹形結構可以知道,每個窗口組件都爲同一類型對象,一個對象可以包含同類型的多個對象。所以我們可以抽象一個組件對象,定義出具有的功能,然後每個窗口的中的組件就可以去分別實例化,最終按照圖中的樹形結構組合到一起。
模式中最簡定義兩個角色即可,一個組件抽象類,一個組件抽象的實現。

/**
 * 定義的組件抽象類
 */
public abstract class Component {

    public abstract void print();
    public abstract void add(Component c);

}

/**
 * 用於實例化的組件實現類
 */
public class SubComponent extends Component {

    private String subComponentName;

    public SubComponent(String name){
        subComponentName = name;
    }

    private List<Component> list;

    @Override
    public void print(){
        if( ObjectUtils.isEmpty(list) ){
            System.out.println("I am "+subComponentName+" !");
            return;
        }
        for (Component c:list){
            c.print();
        }
    }

    @Override
    public void add(Component c){
        if( ObjectUtils.isEmpty(list) ) {
            list = new ArrayList<>();
        }
        list.add(c);
    }

}

/**
 * 測試類
 */
public class TestCombination {

    public static void main(String[] args) {

        Component winForm = new SubComponent("WinForm窗口");
        Component picture = new SubComponent("Picture圖片");
        Component login = new SubComponent("Button-login-登錄");
        Component register = new SubComponent("Button-register-註冊");
        Component frame = new SubComponent("FRAME1");

        Component label1 = new SubComponent("Label-用戶名");
        Component textBox1 = new SubComponent("TextBox-文本框");
        Component label2 = new SubComponent("Lable-密碼");
        Component passwordBox = new SubComponent("PassWordBox-密碼框");
        Component checkbox = new SubComponent("CheckBox-複選框");
        Component textBox2 = new SubComponent("TextBox-記住用戶名");
        Component linkLabel = new SubComponent("LinkLabel-忘記密碼");

        frame.add(label1);
        frame.add(textBox1);
        frame.add(label2);
        frame.add(passwordBox);
        frame.add(checkbox);
        frame.add(textBox2);
        frame.add(linkLabel);

        winForm.add(picture);
        winForm.add(login);
        winForm.add(register);
        winForm.add(frame);

        winForm.print();
    }

}

組件模式很簡單,實現的功能卻很直接,大家可以多思考一下,每種設計模式其實是實際模型的一個抽象。如上文中的例子我們其實還可以組合模式+策略模型+模板方法模式去擴充,就看大家實際情況的應用了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章