設計模式---組合模式

来源: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
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...