設計模式---組合模式

来源:https://www.cnblogs.com/buzuweiqi/archive/2022/09/27/16729556.html
-Advertisement-
Play Games

簡述 類型:結構型 目的:將對象集合組合成樹形結構,使客戶端可以以一致的方式處理單個對象(葉子節點)和組合對象(根節點) 話不多說,上優化案例。 優化案例 最初版v0 不使用組合模式。 現有一個文件和目錄的管理模塊。如樣例。 public class File { // 文件類 private St ...


簡述

  • 類型:結構型
  • 目的:將對象集合組合成樹形結構,使客戶端可以以一致的方式處理單個對象(葉子節點)組合對象(根節點)

話不多說,上優化案例。

優化案例

最初版v0

不使用組合模式。
現有一個文件和目錄的管理模塊。如樣例。

public class File { // 文件類
    private String path;
    private Directory parent;
    public File(Directory dir, String path) {
        if (dir == null)
            throw new RuntimeException("輸入的dir不正確!");
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.parent = dir;
        this.path = dir.getPath() + path;
        dir.add(this);
    }
    public String getPath() {
        return this.path;
    }
}
public class Directory { // 目錄類
    private String path;
    private List<Directory> dirs = new ArrayList<>();
    private List<File> files = new ArrayList<>();
    public Directory(String path) {
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.path = path;
    }
    public Directory(Directory parent, String path) {
        if (parent == null)
            throw new RuntimeException("輸入的parent不正確!");
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.path = parent.getPath() + path;
        parent.add(this);
    }
    public boolean add(File target) {
        for (File file : files)
            // 不能創建同名文件
            if (target.getPath().equals(file.getPath())) return false;
        files.add(target);
        return true;
    }
    public boolean add(Directory target) {
        for (Directory dir : dirs)
            // 不能創建同名目錄
            if (target.getPath().equals(dir.getPath())) return false;
        dirs.add(target);
        return true;
    }
    public boolean remove(Directory target) {
        for (Directory dir : dirs)
            if (target.getPath().equals(dir.getPath())) {
                dirs.remove(dir);
                return true;
            }
        return false;
    }
    public boolean remove(File target) {
        for (File file : files)
            if (target.getPath().equals(file.getPath())) {
                files.remove(file);
                return true;
            }
        return false;
    }
    public String getPath() {
        return this.path;
    }
    public List<Directory> getDirs() {
        return this.dirs;
    }
    public List<File> getFiles() {
        return this.files;
    }
}

不使用組合模式,我們來看看客戶端的使用。

public class Client { // 客戶端
    public static void main(String[] args) {
        // 創建各級目錄
        Directory root = new Directory("/root");
        Directory home = new Directory(root, "/home");
        Directory user1 = new Directory(home, "/user1");
        Directory text = new Directory(user1, "/text");
        Directory image = new Directory(user1, "/image");
        Directory png = new Directory(image, "/png");
        Directory gif = new Directory(image, "/gif");
        // 創建文件
        File f1 = new File(text, "/f1.txt");
        File f2 = new File(text, "/f2.txt");
        File f3 = new File(png, "/f3.png");
        File f4 = new File(gif, "/f4.gif");
        File f5 = new File(png, "/f5.png");
        // 輸出root下的文件或者目錄路徑
        print(root);
    }
    // 前序遍歷目錄下路徑
    public static void print(Directory root) {
        System.out.println(root.getPath());
        List<Directory> dirs = root.getDirs();
        List<File> files = root.getFiles();
        for (int i = 0; i < dirs.size(); i ++) {
            print(dirs.get(i));
        }
        for (int i = 0; i < files.size(); i ++) {
            System.out.println(files.get(i).getPath());
        }
    }
}

可以看到print方法的實現比較複雜,因為FileDirectory是完全不同類型,所以只能對其分別處理。

如何讓客戶端對於FileDirectory採用一致的處理方式?用組合模式啊!!!

修改版v1(透明組合模式)

public interface Node { // 從File和Directory中抽象出Node類
    boolean add(Node node);
    boolean remove(Node node);
    List<Node> getChildren();
    String getPath();
}
public class File implements Node {
    private String path;
    private Node parent;
    public File(Node parent, String path) {
        if (parent == null)
            throw new RuntimeException("輸入的dir不正確!");
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.parent = parent;
        this.path = parent.getPath() + path;
        parent.add(this);
    }
    public boolean add(Node node) { // 因為不是容器,所以重寫這個方法無意義
        throw new RuntimeException("不支持此方法!");
    }
    public boolean remove(Node node) { // 同上
        throw new RuntimeException("不支持此方法!");
    }
    public List<Node> getChildren() { // 同上
        throw new RuntimeException("不支持此方法!");
    }
    public String getPath() {
        return this.path;
    }
}
public class Directory implements Node {
    private String path;
    private List<Node> children = new ArrayList<>();
    public Directory(String path) {
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.path = path;
    }
    public Directory(Node parent, String path) {
        if (parent == null)
            throw new RuntimeException("輸入的parent不正確!");
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.path = parent.getPath() + path;
        parent.add(this);
    }
    public boolean add(Node target) {
        for (Node node : children)
            // 不能創建同名文件
            if (target.getPath().equals(node.getPath())) return false;
        children.add(target);
        return true;
    }
    public boolean remove(Node target) {
        for (Node node : children)
            if (target.getPath().equals(node.getPath())) {
                children.remove(node);
                return true;
            }
        return false;
    }
    public String getPath() {
        return this.path;
    }
    public List<Node> getChildren() {
        return this.children;
    }
}

通過在FileDirectory的高層新增Node介面,面向介面編程加上FileDirectory形成的樹形結構使得客戶端可以很自然地一致處理FileDirectory。來看看客戶端代碼。

public class Client {
    public static void main(String[] args) {
        // 創建各級目錄
        Node root = new Directory("/root");
        Node home = new Directory(root, "/home");
        Node user1 = new Directory(home, "/user1");
        Node text = new Directory(user1, "/text");
        Node image = new Directory(user1, "/image");
        Node png = new Directory(image, "/png");
        Node gif = new Directory(image, "/gif");
        // 創建文件
        Node f1 = new File(text, "/f1.txt");
        Node f2 = new File(text, "/f2.txt");
        Node f3 = new File(png, "/f3.png");
        Node f4 = new File(gif, "/f4.gif");
        Node f5 = new File(png, "/f5.png");
        // 輸出root下的文件或者目錄路徑
        print(root);
    }
    public static void print(Node root) {
        System.out.println(root.getPath());
        List<Node> nodes = root.getChildren();
        for (int i = 0; i < nodes.size(); i ++) {
            Node node = nodes.get(i);
            if (node instanceof File) {
                System.out.println(node.getPath());
                continue;
            }
            print(node);
        }
    }
}

別高興的太早了,雖然我們實現了最初的需求,但是有一處的代碼不是很健康。在File中有三個方法實際上並沒有被實現,有些臃腫。

修改版v2(安全組合模式)

public interface Node { // 從File和Directory中抽象出Node類
    String getPath(); // 刪除累贅的方法
}
public class File implements Node {
    private String path;
    private Node parent;
    public File(Directory parent, String path) {
        if (parent == null)
            throw new RuntimeException("輸入的dir不正確!");
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.parent = parent;
        this.path = parent.getPath() + path;
        parent.add(this);
    }
    public String getPath() {
        return this.path;
    }
}
public class Directory implements Node {
    private String path;
    private List<Node> children = new ArrayList<>();
    public Directory(String path) {
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.path = path;
    }
    public Directory(Directory parent, String path) {
        if (parent == null)
            throw new RuntimeException("輸入的parent不正確!");
        if (path == null || path == "")
            throw new RuntimeException("輸入的path不正確!");
        this.path = parent.getPath() + path;
        parent.add(this);
    }
    public boolean add(Node target) {
        for (Node node : children)
            // 不能創建同名文件
            if (target.getPath().equals(node.getPath())) return false;
        children.add(target);
        return true;
    }
    public boolean remove(Node target) {
        for (Node node : children)
            if (target.getPath().equals(node.getPath())) {
                children.remove(node);
                return true;
            }
        return false;
    }
    public String getPath() {
        return this.path;
    }
    public List<Node> getChildren() {
        return this.children;
    }
}

修改Node介面的抽象方法後代碼清爽了很多。客戶端調用需要稍微修改下。

public class Client {
    public static void main(String[] args) {
        // 創建各級目錄
        Directory root = new Directory("/root");
        Directory home = new Directory(root, "/home");
        Directory user1 = new Directory(home, "/user1");
        Directory text = new Directory(user1, "/text");
        Directory image = new Directory(user1, "/image");
        Directory png = new Directory(image, "/png");
        Directory gif = new Directory(image, "/gif");
        // 創建文件
        File f1 = new File(text, "/f1.txt");
        File f2 = new File(text, "/f2.txt");
        File f3 = new File(png, "/f3.png");
        File f4 = new File(gif, "/f4.gif");
        File f5 = new File(png, "/f5.png");
        // 輸出root下的文件或者目錄路徑
        print(root);
    }
    public static void print(Directory root) {
        System.out.println(root.getPath());
        List<Node> nodes = root.getChildren();
        for (int i = 0; i < nodes.size(); i ++) {
            Node node = nodes.get(i);
            if (nodes.get(i) instanceof File) {
                System.out.println(node.getPath());
                continue;
            }
            print((Directory) node); // 增加強轉
        }
    }
}

其實透明組合模式和安全組合模式看著用就好了,其實問題不大的。

總結

優點

  1. 讓客戶端可以一致地處理單一對象和組合對象。

缺點

  1. 局限性太強,只有可以構成樹形結構的對象集合才可以使用。

適用場景

  1. 只有在對象集合可以組合成樹形結構時才可以使用。

本文來自博客園,作者:buzuweiqi,轉載請註明原文鏈接:https://www.cnblogs.com/buzuweiqi/p/16729556.html


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1 CMD 規範介紹 CMD: Common Module Definition, 通用模塊定義。與 AMD 規範類似,也是用於瀏覽器端,非同步載入模塊,一個文件就是一個模塊,當模塊使用時才會載入執行。其語法與 AMD 規範很類似。 1.1 定義模塊 定義模塊使用 define 函數: define( ...
  • uniapp webview h5 通信 window.postMessage 方式 父頁面 <template> <view> <!-- <web-view :webview-styles="webviewStyles" src="https://uniapp.dcloud.io/static/w ...
  • 模塊 HTML 網頁中,瀏覽器通過<script>標簽載入 JavaScript 腳本。 <!-- 頁面內嵌的腳本 --> <script type="application/javascript"> // module code </script> <!-- 外部腳本 --> <script ty ...
  • 命令模式(Command Pattern)是一種數據驅動的設計模式,它屬於行為型模式。請求以命令的形式包裹在對象中,並傳給調用對象。調用對象尋找可以處理該命令的合適的對象,並把該命令傳給相應的對象,該對象執行命令。 ...
  • 橋接模式是一種在日常開發中不是特別常用的設計模式,主要是因為上手難度較大,但是對於理解面向對象設計有非常大的幫助。 ...
  • 在項目編碼中經常會遇到一些新的需求試圖復用已有的功能邏輯進行實現的場景,但是已有的邏輯又不能完全滿足新需求的要求,所以就會出現各種生搬硬套的操作。本篇文檔就一起來聊一聊如何藉助Adapter實現高效復用已有邏輯、讓代碼復用起來更加的得體與優雅。 ...
  • 【1】前言 本篇幅是對 線程池底層原理詳解與源碼分析 的補充,預設你已經看完了上一篇對ThreadPoolExecutor類有了足夠的瞭解。 【2】ScheduledThreadPoolExecutor的介紹 1.ScheduledThreadPoolExecutor繼承自ThreadPoolExe ...
  • 概述 tomcat亂碼問題相信大家肯定都遇見過,本篇將詳細介紹有關Tomcat的各種亂碼問題原因和解決方法😊 原因 首先亂碼問題的原因通俗的講就是讀的編碼格式和寫的解碼格式不一致,比如最常見的兩種中文編碼UTF-8和GBK,UTF-8一個漢字占三個位元組,GBK一個漢字占兩個位元組,所以當編碼與解碼格 ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...