天天看點

Java描述設計模式(10):組合模式一、生活場景二、組合模式-安全式三、組合模式-透明式四、JDK中應用五、源代碼位址

本文源碼: GitHub·點這裡 || GitEE·點這裡

一、生活場景

1、檔案系統

下圖是常見的計算機檔案系統的一部分。

Java描述設計模式(10):組合模式一、生活場景二、組合模式-安全式三、組合模式-透明式四、JDK中應用五、源代碼位址

檔案系統是一個樹結構,樹上長有節點。樹的節點有兩種:

  • 樹枝節點
即檔案夾,有内部樹結構,在圖中塗有顔色;
  • 樹葉節點
另一種是檔案,即樹葉節點,沒有内部樹結構。

2、列印檔案樹結構

public class C01_InScene {
    public static void main(String[] args) {
        File file = new File("F:\\tree") ;
        fileTree(file, 0);
    }
    private static void fileTree(File file, int floor) {
        // 判斷是否存在
        if (file.exists()) {
            if (floor > 0) {
                // 循環打空格
                for (int i = 0; i < floor; i++) {
                    System.out.print(" ");
                }
            }
            if (file.isDirectory()) {
                System.out.println("+" + file.getName());
                // 列出所有檔案及檔案夾
                File[] files = file.listFiles();
                if (null != files) {
                    // 循環遞歸
                    for (File dirFile : files) {
                        fileTree(dirFile, floor + 1);
                    }
                }
            } else {
                System.out.println("-" + file.getName());
            }
        }
    }
}           

執行效果:+代表檔案夾,-代表檔案。

+tree
 +dir1
  +dir2
   -dir2Leaf.txt
  -leaf1.txt
  -leaf2.txt
 -OneLeaf.txt
 -TwoLeaf.txt           

3、組合模式描述

組合模式屬于對象的結構模式,有時又叫做“部分——整體”模式。組合模式将對象組織到樹結構中,可以用來描述整體與部分的關系。組合模式可以使用戶端将單純元素與複合元素同等看待。

二、組合模式-安全式

1、基礎概念

安全式的組合模式要求管理聚集的方法隻出現在樹枝構件類中,而不出現在樹葉構件類中。涉及到三個角色:
  • 抽象構件(Component)角色
它給組合的對象定義出公共的接口及其預設行為,可以用來管理所有的子對象。組合對象通常把它所包含的子對象當做類型為Component的對象。在安全式的組合模式裡,構件角色并不定義出管理子對象的方法,這一定義由樹枝構件對象給出。
  • 樹葉構件(Leaf)角色
樹葉對象是沒有下級子對象的對象,定義出參加組合的原始對象的行為。
  • 樹枝構件(Composite)角色
代表參加組合的有下級子對象的對象。樹枝構件類給出所有的管理子對象的方法,如add()、remove()以及getChild()。

2、模式圖解

Java描述設計模式(10):組合模式一、生活場景二、組合模式-安全式三、組合模式-透明式四、JDK中應用五、源代碼位址

3、源代碼實作

public class C02_Security_Model {
    public static void main(String[] args) {
        Composite root = new Composite("服裝");
        Composite composite1 = new Composite("男裝");
        Leaf manCoat = new Leaf("上衣");
        Leaf manBottom = new Leaf("下衣");
        composite1.addChild(manCoat);
        composite1.addChild(manBottom);
        Composite composite2 = new Composite("女裝");
        Leaf leaf1 = new Leaf("鞋子");
        Leaf leaf2 = new Leaf("帽子");
        root.addChild(leaf1);
        root.addChild(leaf2);
        root.addChild(composite1);
        root.addChild(composite2);
        root.printStruct("");
    }
}
// 抽象構件角色類
interface Component {
    /*
     * 輸出元件自身的名稱
     */
    void printStruct(String preStr);
}
// 樹枝構件角色類
class Composite implements Component{
    // 用來存儲組合對象中包含的子元件對象
    private List<Component> childComponents = new ArrayList<Component>();
    // 輸出對象的名稱
    private String name;
    // 構造方法,傳入組合對象的名字
    public Composite (String name){
        this.name = name;
    }
    /**
     * 聚集管理方法,增加一個子構件對象
     * @param child 子構件對象
     */
    public void addChild(Component child){
        childComponents.add(child);
    }
    /**
     * 聚集管理方法,删除一個子構件對象
     * @param index 子構件對象的下标
     */
    public void removeChild(int index){
        childComponents.remove(index);
    }
    /**
     * 聚集管理方法,傳回所有子構件對象
     */
    public List getChild(){
        return childComponents ;
    }
    /**
     * 輸出對象的自身結構
     * @param preStr 字首,主要是按照層級拼接空格,實作向後縮進
     */
    @Override
    public void printStruct(String preStr) {
        //先輸出自己
        System.out.println(preStr+"+"+this.name);
        //如果還包含有子元件,那麼就輸出這些子元件對象
        if (this.childComponents != null){
            //添加兩個空格,表示向後縮進兩個空格
            preStr = preStr+"  ";
            //輸出目前的子對象:使用函數遞歸的原理
            for (Component c : childComponents) {
                c.printStruct(preStr);
            }
        }
    }
}
class Leaf implements Component{
    // 輸出葉子對象的名稱
    private String name;
    // 構造方法,傳入葉子對象的名稱
    public Leaf (String name){
        this.name = name ;
    }
    /**
     * 輸出葉子對象的結構,葉子對象沒有子對象,也就是輸出葉子對象的名字
     * @param preStr 字首,主要是按照層級拼接的空格,實作向後縮進
     */
    @Override
    public void printStruct(String preStr) {
        System.out.println(preStr+"-"+name);
    }
}           
  • 輸出結果
+服裝
  -鞋子
  -帽子
  +男裝
    -上衣
    -下衣
  +女裝           

三、組合模式-透明式

1、概念圖解

與安全式的組合模式不同的是,透明式的組合模式要求所有的具體構件類,不論樹枝構件還是樹葉構件,均符合一個固定接口。
Java描述設計模式(10):組合模式一、生活場景二、組合模式-安全式三、組合模式-透明式四、JDK中應用五、源代碼位址

2、源代碼實作

public class C03_Transparent_Model {
    public static void main(String[] args) {
        Component1 root = new Composite1("服裝");
        Component1 c1 = new Composite1("男裝");
        Component1 c2 = new Composite1("女裝");
        Component1 leaf1 = new Leaf1("襯衫");
        Component1 leaf2 = new Leaf1("夾克");
        Component1 leaf3 = new Leaf1("裙子");
        Component1 leaf4 = new Leaf1("套裝");
        root.addChild(c1);
        root.addChild(c2);
        c1.addChild(leaf1);
        c1.addChild(leaf2);
        c2.addChild(leaf3);
        c2.addChild(leaf4);
        root.printStruct("");
    }
}
abstract class Component1 {
    /**
     * 輸出元件自身的名稱
     */
    public abstract void printStruct(String preStr);
    // 聚集管理方法,增加一個子構件對象
    public void addChild(Component1 child){
        /**
         * 預設實作,抛出異常,因為葉子對象沒有此功能
         * 或者子元件沒有實作這個功能
         */
        throw new UnsupportedOperationException("對象不支援此功能");
    }
    // 聚集管理方法,删除一個子構件對象
    public void removeChild(int index){
        /**
         * 預設實作,抛出異常,因為葉子對象沒有此功能
         * 或者子元件沒有實作這個功能
         */
        throw new UnsupportedOperationException("對象不支援此功能");
    }
    // 聚集管理方法,傳回所有子構件對象
    public List<Component1> getChild(){
        /**
         * 預設實作,抛出異常,因為葉子對象沒有此功能
         * 或者子元件沒有實作這個功能
         */
        throw new UnsupportedOperationException("對象不支援此功能");
    }
}
class Composite1 extends Component1 {
    // 用來存儲組合對象中包含的子元件對象
    private List<Component1> childComponents = new ArrayList<Component1>();
    // 輸出對象名稱
    private String name ;
    public Composite1 (String name){
        this.name = name;
    }
    /**
     * 聚集管理方法,增加一個子構件對象
     * @param child 子構件對象
     */
    public void addChild(Component1 child){
        childComponents.add(child);
    }
    /**
     * 聚集管理方法,删除一個子構件對象
     * @param index 子構件對象的下标
     */
    public void removeChild(int index){
        childComponents.remove(index);
    }
    // 聚集管理方法,傳回所有子構件對象
    public List<Component1> getChild(){
        return childComponents ;
    }
    /**
     * 輸出對象的自身結構
     * @param preStr 字首,主要是按照層級拼接空格,實作向後縮進
     */
    @Override
    public void printStruct(String preStr) {
        // 首先輸出自己名稱
        System.out.println(preStr+"+"+this.name);
        // 如果還包含有子元件,那麼就輸出這些子元件對象
        preStr = preStr + "  ";
        if (this.childComponents != null) {
            // 添加兩個空格,表示向後縮進
            for (Component1 c : childComponents) {
                ////遞歸輸出每個子對象
                c.printStruct(preStr);
            }
        }
    }
}
class Leaf1 extends Component1 {
    private String name;
    public Leaf1 (String name){
        this.name = name;
    }
    /**
     * 輸出葉子對象的結構,葉子對象沒有子對象,也就是輸出葉子對象的名字
     * @param preStr 字首,主要是按照層級拼接的空格,實作向後縮進
     */
    @Override
    public void printStruct(String preStr) {
        System.out.println(preStr+"-"+name);
    }
}           

四、JDK中應用

1、HashMap結構圖

Java描述設計模式(10):組合模式一、生活場景二、組合模式-安全式三、組合模式-透明式四、JDK中應用五、源代碼位址

2、分層結構

  • interface Map
  • class AbstractMap implements Map
  • HashMap extends AbstractMap implements Map
  • interface Map.Entry
  • Node implements Map.Entry

3、源代碼

  • 存儲葉子節點
public V put(K var1, V var2) {
    return this.putVal(hash(var1), var1, var2, false, true);
}
final V putVal(int var1, K var2, V var3, boolean var4, boolean var5) {
    HashMap.Node[] var6 = this.table;
    .......
}           
  • 存儲樹枝節點
public void putAll(Map<? extends K, ? extends V> var1) {
    this.putMapEntries(var1, true);
}           

五、源代碼位址

GitHub·位址
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·位址
https://gitee.com/cicadasmile/model-arithmetic-parent