設計模式---組合模式

来源: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
  • 周末,寫點簡單的水一下。 新版本的vs創建項目的時候可以選擇自帶一個swagger。然而這隻是基本的swagger功能。 幾個介面無所謂啦,隨著介面越來越多,就這麼丟給你,一時間也會懵逼,所以這篇文章要做的有兩個功能。 給swagger文檔添加註釋 給swagger添加切換“版本”的功能(也可以理解 ...
  • 大家好,我是沙漠盡頭的狼。 本文首發於Dotnet9,介紹使用Lib.Harmony庫攔截第三方.NET庫方法,達到不修改其源碼並能實現修改方法邏輯、預期行為的效果,並且不限於只攔截public訪問修飾的類及方法,行文目錄: 什麼是方法攔截? 示常式序攔截 非public方法怎麼攔截? 總結 1. ...
  • 問題代碼: xmal:一個按鈕+一個顯示框 1 <Button Width="100" Height="50" Margin="10" Click="Button_Click">test</Button> 2 <TextBox x:Name="display" Width="300" Height= ...
  • 前置條件 ​ 阿裡雲伺服器一臺(可在購買伺服器時勾選安裝寶塔選項,免去後面的寶塔安裝) ​ 設置阿裡雲伺服器密碼並登陸伺服器 ​ 以下操作均在伺服器Linux中進行(使用遠程連接工具登錄) 寶塔登錄 登錄阿裡雲伺服器在Linux命令行中輸入bt,查看寶塔信息 ​ 根據寶塔信息提供的網站登陸寶塔服務( ...
  • GetTokenInformation 用於檢索進程或線程的令牌(Token)信息。Token是一個數據結構,其包含有關進程或線程的安全上下文,代表當前用戶或服務的安全標識符和許可權信息。GetTokenInformation函數也可以用來獲取這些安全信息,通常用於在運行時檢查某個進程或線程的許可權或安... ...
  • matplotlib 在1.0版本之前其實是不支持3D圖形繪製的。 後來的版本中,matplotlib加入了3D圖形的支持,不僅僅是為了使數據的展示更加生動和有趣。更重要的是,由於多了一個維度,擴展了其展示數據分佈和關係的能力,可以一次從三個維度來比較數據。 下麵介紹在matplotlib中繪製各類 ...
  • 編寫一個App就能編譯發佈到iOS、Android和Web等各大平臺的跨平臺技術,各大廠商一直都有研究和發佈對應技術產品,目前最熱門的莫過於Flutter框架了。而Dart作為其唯一的編程語言,今天我們開始來體驗一下…… ...
  • 實現基本的線程池 前提:我們要實現的線程池有如下功能: 基本的線程池模型 能提交和運行任務 能正常關閉線程池 線程的拒絕策略 線程池擴容 縮容線程池 代碼地址: 1、線程池的介紹? 線程池是什麼? 線程池是一種利用池化技術來管理線程的一種技術。 當沒有線程池的時候,我們如何創建線程? 繼承Threa ...
  • SDRAM基本信息 儲存能力計算 4X16X4=256(Mbit),註意不是MByte SDRAM控制 sdram包含兩個部分:sdram_ctrl、fifo_ctrl。 sdram_ctrl:其頂層為SDRAM的控制模塊內部實例化了5個模塊,有初始化、自刷新、寫和讀模塊,還有一個仲裁模塊對這四個不 ...
  • 歡迎訪問我的GitHub 這裡分類和彙總了欣宸的全部原創(含配套源碼):https://github.com/zq2599/blog_demos 本篇概覽 欣宸正在為接下新的Java雲原生實戰系列原創做準備,既然是實戰,少不了一套雲原生環境,以下內容是必不可少的: linux操作系統 kuberne ...