設計模式---組合模式

来源: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、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...