設計模式-結構性模式

結構型模式主要關注類或對象的組合,旨在通過識別簡單的結構關系來設計更復雜的結構。以下是幾種常見的結構型設計模式:

1. 適配器模式(Adapter Pattern)

    • 將一個類的接口轉換成客戶端所期望的另一個接口,使得原本由于接口不兼容而不能一起工作的那些類可以一起工作。
    • 適用于需要使用現有類但其接口不符合需求的情況。

假設我們有一個舊的MediaPlayer接口,它只能播放.mp3文件。現在我們需要一個新功能,能夠播放.wav格式的文件。我們可以使用適配器模式來解決這個問題。

// 已有的MediaPlayer接口
interface MediaPlayer {void play(String audioType, String fileName);
}// 實現了MediaPlayer接口的類
class AudioPlayer implements MediaPlayer {@Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase("mp3")) {System.out.println("Playing mp3 file. Name: " + fileName);} else {System.out.println("Invalid media. " + audioType + " format not supported");}}
}// 新的AdvancedMediaPlayer接口及其實現類
interface AdvancedMediaPlayer {void playWav(String fileName);
}class WavPlayer implements AdvancedMediaPlayer {@Overridepublic void playWav(String fileName) {System.out.println("Playing wav file. Name: " + fileName);}
}// 創建適配器類
class MediaAdapter implements MediaPlayer {private AdvancedMediaPlayer advancedMusicPlayer;public MediaAdapter() {advancedMusicPlayer = new WavPlayer();}@Overridepublic void play(String audioType, String fileName) {if(audioType.equalsIgnoreCase("wav")) {advancedMusicPlayer.playWav(fileName);}}
}// 使用適配器
public class AdapterPatternDemo {public static void main(String[] args) {MediaPlayer audioPlayer = new AudioPlayer();audioPlayer.play("mp3", "song.mp3");audioPlayer.play("wav", "song.wav"); // 這里會顯示不支持MediaPlayer mediaAdapter = new MediaAdapter();mediaAdapter.play("wav", "song.wav"); // 現在可以播放wav文件}
}

2. 橋接模式(Bridge Pattern)

    • 將抽象部分與它的實現部分分離,使它們都可以獨立變化。
    • 適用于當不想在抽象和實現之間建立固定的綁定關系時,例如圖形庫中形狀和顏色的組合。

假設我們有一個繪圖應用程序,它可以繪制不同形狀,并且這些形狀可以用不同的顏色繪制。為了使形狀和顏色獨立變化,我們可以使用橋接模式。

// 顏色接口
interface Color {void applyColor();
}// 具體的顏色實現
class RedColor implements Color {@Overridepublic void applyColor() {System.out.println("Red color applied.");}
}class BlueColor implements Color {@Overridepublic void applyColor() {System.out.println("Blue color applied.");}
}// 抽象的形狀類,持有Color對象的引用
abstract class Shape {protected Color color;public Shape(Color color) {this.color = color;}abstract void draw();
}// 具體的形狀實現
class Circle extends Shape {public Circle(Color color) {super(color);}@Overridevoid draw() {System.out.print("Drawing Circle. ");color.applyColor();}
}// 使用橋接模式
public class BridgePatternDemo {public static void main(String[] args) {Shape redCircle = new Circle(new RedColor());redCircle.draw(); // 輸出:Drawing Circle. Red color applied.Shape blueCircle = new Circle(new BlueColor());blueCircle.draw(); // 輸出:Drawing Circle. Blue color applied.}
}

3. 組合模式(Composite Pattern)

    • 允許將對象組合成樹形結構以表示“部分-整體”的層次結構,使得用戶對單個對象和組合對象的使用具有一致性。
    • 常用于文件系統、菜單等層次化結構的場景。

假設我們有一個組織結構,包括員工和部門。每個部門可能包含多個員工和其他部門。我們可以使用組合模式來處理這種“部分-整體”的層次結構。

// 組件接口
interface Employee {void showEmployeeDetails();
}// 葉子節點
class Developer implements Employee {private String name;private long empId;public Developer(String name, long empId) {this.name = name;this.empId = empId;}@Overridepublic void showEmployeeDetails() {System.out.println("Developer Name: " + name + ", EmpId: " + empId);}
}// 組合部件
class Manager implements Employee {private List<Employee> employees = new ArrayList<>();public void addEmployee(Employee emp) {employees.add(emp);}public void removeEmployee(Employee emp) {employees.remove(emp);}@Overridepublic void showEmployeeDetails() {for (Employee emp : employees) {emp.showEmployeeDetails();}}
}// 使用組合模式
public class CompositePatternDemo {public static void main(String[] args) {Employee dev1 = new Developer("John", 1001L);Employee dev2 = new Developer("Jane", 1002L);Manager manager = new Manager();manager.addEmployee(dev1);manager.addEmployee(dev2);Employee dev3 = new Developer("Doe", 1003L);manager.addEmployee(dev3);manager.showEmployeeDetails();}
}

4. 裝飾模式(Decorator Pattern)

    • 動態地給一個對象添加一些額外的職責,就增加功能來說,比生成子類更為靈活。
    • 適用于需要動態地為對象添加功能而不改變原有代碼的情況,如Java中的I/O流。

裝飾模式允許你通過創建一個包裝對象動態地向一個對象添加功能,而不需要修改其結構。

// 基礎組件接口
interface Coffee {double getCost(); // 獲取成本String getDescription(); // 獲取描述
}// 具體組件實現
class SimpleCoffee implements Coffee {@Overridepublic double getCost() { return 10; } // 簡單咖啡的成本@Overridepublic String getDescription() { return "Simple Coffee"; }
}// 裝飾器抽象類
abstract class CoffeeDecorator implements Coffee {protected Coffee decoratedCoffee;public CoffeeDecorator(Coffee c) {this.decoratedCoffee = c;}@Overridepublic double getCost() { return decoratedCoffee.getCost(); }@Overridepublic String getDescription() { return decoratedCoffee.getDescription(); }
}// 牛奶裝飾器
class MilkDecorator extends CoffeeDecorator {public MilkDecorator(Coffee c) { super(c); }@Overridepublic double getCost() { return super.getCost() + 2; }@Overridepublic String getDescription() { return super.getDescription() + ", Milk"; }
}// 使用裝飾模式
public class DecoratorPatternDemo {public static void main(String[] args) {Coffee myCoffee = new MilkDecorator(new SimpleCoffee());System.out.println("Cost: " + myCoffee.getCost());System.out.println("Description: " + myCoffee.getDescription());}
}

5. 外觀模式(Facade Pattern)

    • 為子系統中的一組接口提供一個一致的界面,定義了一個高層接口,這個接口使得這一子系統更加容易使用。
    • 適用于簡化復雜系統的接口,如數據庫連接管理。

外觀模式提供了一個統一的接口,用來訪問子系統中的一群接口。它提供了一個高層次的接口,使得子系統更易于使用。

// 子系統類
class CPU {public void processData() { System.out.println("Processing data."); }
}class Memory {public void load() { System.out.println("Loading data from memory."); }
}class HardDrive {public void readData() { System.out.println("Reading data from hard drive."); }
}// 外觀類
class ComputerFacade {private CPU cpu;private Memory memory;private HardDrive hardDrive;public ComputerFacade() {this.cpu = new CPU();this.memory = new Memory();this.hardDrive = new HardDrive();}public void startComputer() {memory.load();hardDrive.readData();cpu.processData();}
}// 使用外觀模式
public class FacadePatternDemo {public static void main(String[] args) {ComputerFacade computer = new ComputerFacade();computer.startComputer();}
}

6. 享元模式(Flyweight Pattern)

    • 運用共享技術有效地支持大量細粒度的對象。
    • 適用于需要創建大量相似對象且內存占用成為問題的情況,如文本編輯器中的字符對象。

享元模式主要用于減少創建對象的數量,以減少內存占用和提高性能。它通過共享盡可能多的對象來做到這一點。

// 享元接口
interface Shape {void draw(String color);
}// 具體享元類
class Circle implements Shape {private String color;public Circle(String color) {this.color = color;}@Overridepublic void draw(String fillColor) {System.out.println("Drawing Circle [Color: " + color + ", FillColor: " + fillColor + "]");}
}// 享元工廠
class ShapeFactory {private static final HashMap<String, Shape> circleMap = new HashMap<>();public static Shape getCircle(String color) {Circle circle = (Circle)circleMap.get(color);if(circle == null) {circle = new Circle(color);circleMap.put(color, circle);System.out.println("Creating circle of color: " + color);}return circle;}
}// 使用享元模式
public class FlyweightPatternDemo {public static void main(String[] args) {ShapeFactory shapeFactory = new ShapeFactory();Shape shape1 = shapeFactory.getCircle("Red");shape1.draw("Dark Red");Shape shape2 = shapeFactory.getCircle("Red"); // 不會創建新對象shape2.draw("Light Red");}
}

7. 代理模式(Proxy Pattern)

    • 為其他對象提供一種代理以控制對這個對象的訪問。
    • 適用于需要在訪問對象時加入額外處理邏輯的情況,如遠程調用、權限檢查等。

代理模式為其他對象提供一種代理以控制對這個對象的訪問。

// 主題接口
interface Image {void display();
}// 真實主題類
class RealImage implements Image {private String fileName;public RealImage(String fileName) {this.fileName = fileName;loadFromDisk(fileName);}@Overridepublic void display() {System.out.println("Displaying " + fileName);}private void loadFromDisk(String fileName) {System.out.println("Loading " + fileName);}
}// 代理類
class ProxyImage implements Image {private RealImage realImage;private String fileName;public ProxyImage(String fileName) {this.fileName = fileName;}@Overridepublic void display() {if(realImage == null) {realImage = new RealImage(fileName);}realImage.display();}
}// 使用代理模式
public class ProxyPatternDemo {public static void main(String[] args) {Image image = new ProxyImage("test_10mb.jpg");// 圖像將從磁盤加載image.display();System.out.println("");// 圖像不會從磁盤加載image.display();}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/70623.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/70623.shtml
英文地址,請注明出處:http://en.pswp.cn/web/70623.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

VantUI官網更新2025,移動端前端開發

Vant 2 - Mobile UI Components built on Vue https://vant-ui.github.io/vant/v2/#/zh-CN/quickstart Vant 4 - A lightweight, customizable Vue UI library for mobile web apps. https://vant-ui.github.io/vant/#/zh-CN Vant Weapp - 輕量、可靠的小程序 UI 組件庫,微…

《我的AUTOSAR之路》Det 解析

Det 解析 1. 引言和功能概述2. Errors2.1 開發錯誤(Development Errors)2.2 運行時錯誤(Runtime Errors)2.3 臨時故障(Transient Faults)3 錯誤查詢默認錯誤追蹤器(Default Error Tracer,DET) 1. 引言和功能概述 默認錯誤追蹤器(DET):該規范描述了默認錯誤追蹤器(…

電腦連接示波器顯示波形

通過網線連接示波器和電腦&#xff0c;將示波器波形顯示在電腦上直接復制圖片至報告中&#xff0c;以下是配置步驟。 一、設備 網線&#xff0c;Tektronix示波器&#xff0c;電腦 二、使用步驟 1.用網線連接電腦和示波器 2.電腦關掉WiFi&#xff0c;查看IPv4網關地址&#xf…

npm i 失敗權限問題

安裝完node之后, 測試全局安裝一個最常用的 express 模塊進行測試 失敗&#xff0c;但是用管理員權限打開cmd 安裝就成功。 報錯如下&#xff1a; npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and …

上海創智學院(測試)算法筆試(ACM賽制)部分例題

1.第一個題&#xff0c;大概題目意思是求n句話中最長的單詞和最短的單詞 這個題目做的有點磕巴&#xff0c;好幾年沒有寫過c/c了&#xff0c;連string的復制都不會寫了&#xff0c;哈哈哈&#xff0c;太笨了 后面一點點撿起來&#xff0c;還是寫出來了&#xff0c;本身沒啥&…

編寫一個程序,輸出 “Hello, World!“(Python版)

編寫一個程序&#xff0c;輸出 "Hello, World!" 在 Python 中&#xff0c;輸出 “Hello, World!” 的程序非常簡單。你只需要使用 print 函數即可。以下是代碼示例&#xff1a; print("Hello, World!")將這段代碼保存為一個 .py 文件&#xff08;例如 hel…

python實戰項目58:采集蜻蜓FM熱門音頻top排行榜

python實戰項目58:采集蜻蜓FM熱門音頻top排行榜 一、采集流程介紹二、數據接口采集三、使用xpath提取頁面數據1、抓包,找到數據接口2、發送請求,獲取數據3、提取數據4、保存數據一、采集流程介紹 蜻蜓FM熱門音頻top排行榜的鏈接為: https://m.qingting.fm/rank/,首頁如下圖…

【Matlab仿真】Matlab Function中如何使用靜態變量?

背景 根據Simulink的運行機制&#xff0c;每個采樣點會調用一次MATLAB Function的函數&#xff0c;兩次調用之間&#xff0c;同一個變量的前次計算的終值如何傳遞到當前計算周期來&#xff1f;其實可以使用persistent變量實現函數退出和進入時內部變量值的保持。 persistent變…

LaneATT環境配置步驟

本文介紹Ubuntu下配置車道線檢測算法LaneATT代碼運行環境&#xff0c;步驟如下。 1. 從LaneATT官方代碼倉庫下載源碼。也可git直接拉取。 2. 安裝Anaconda或miniconda 。 參考&#xff1a;https://docs.anaconda.com/miniconda/ 3. 創建conda虛擬環境LaneATT&#xff08;環…

【AIGC】使用Python實現科大訊飛語音服務ASR轉錄功能:完整指南

文章目錄 訊飛ASR轉寫API完整指南1. 引言2. 訊飛ASR API介紹3. API參數說明3.1 認證參數3.2 上傳參數3.3 查詢結果參數3.4 orderResult 字段3.5 Lattice 字段3.6 json_1best 字段3.7 st 字段 4. Python代碼實現4.1 生成簽名4.2 上傳音頻文件4.3 獲取轉寫結果4.4 解析轉寫結果 5…

大學本科教務系統設計方案,涵蓋需求分析、架構設計、核心模塊和技術實現要點

以下是大學本科教務系統的設計方案,涵蓋需求分析、架構設計、核心模塊和技術實現要點: 大學本科教務系統設計方案 一、需求分析 1. 核心用戶角色 角色功能需求學生選課/退課、成績查詢、課表查看、學分統計、考試報名、學業預警教師成績錄入、課程大綱上傳、教學進度管理、…

30道Qt面試題(答案公布)

前五個答案 ? 1. Qt中常用的五大模塊是哪些? Qt中常用的五大模塊包括: ? Qt Core:提供核心非GUI功能,如數據結構、文件操作、國際化等。 ? Qt GUI:提供與平臺無關的圖形和基本窗口功能。 ? Qt Widgets:提供用于創建傳統桌面應用程序的UI組件。 ? Qt Netw…

jdk21下載、安裝(Windows、Linux、macOS)

Windows 系統 1. 下載安裝 訪問 Oracle 官方 JDK 下載頁面 或 OpenJDK 下載頁面&#xff0c;根據自己的系統選擇合適的 Windows 版本進行下載&#xff08;通常選擇 .msi 安裝包&#xff09;。 2. 配置環境變量 右鍵點擊 “此電腦”&#xff0c;選擇 “屬性”。 在左側導航欄…

2022年全國職業院校技能大賽網絡系統管理賽項模塊A:網絡構建(樣題6)-網絡部分解析-附詳細代碼

目錄 附錄1:拓撲圖 附錄2:地址規劃表 1.SW1 2.SW2 3.SW3 4.SW4 5.VSU 6.SW7 7.R1 8.R2 9.R3 10.AC1 11.AC2 12.EG1 13.EG2 附錄1:拓撲圖 附錄2:地址規劃表

java項目之網絡游戲交易系統源碼(ssm+mysql)

風定落花生&#xff0c;歌聲逐流水&#xff0c;大家好我是風歌&#xff0c;混跡在java圈的辛苦碼農。今天要和大家聊的是一款基于ssm的網絡游戲交易系統。項目源碼以及部署相關請聯系風歌&#xff0c;文末附上聯系信息 。 項目簡介&#xff1a; 本網絡游戲交易系統分為管理員…

高并發內存池的thread cache部分實現及測試

并發內存池的三個主要組成部分&#xff1a; 線程緩存&#xff08;Thread Cache&#xff09; 每個線程擁有獨立的線程緩存&#xff0c;用于處理小于256KB的內存分配。由于每個線程都有自己的緩存&#xff0c;線程在從線程緩存中分配內存時無需加鎖&#xff0c;這有效避免了競爭…

【紅隊利器】單文件一鍵結束火絨6.0

關于我們 4SecNet 團隊專注于網絡安全攻防研究&#xff0c;目前團隊成員分布在國內多家頂級安全廠商的核心部門&#xff0c;包括安全研究領域、攻防實驗室等&#xff0c;匯聚了行業內的頂尖技術力量。團隊在病毒木馬逆向分析、APT 追蹤、破解技術、漏洞分析、紅隊工具開發等多個…

索提諾比率(Sortino Ratio):更精準的風險調整收益指標(中英雙語)

索提諾比率&#xff08;Sortino Ratio&#xff09;&#xff1a;更精準的風險調整收益指標 &#x1f4c9;&#x1f4ca; &#x1f4cc; 什么是索提諾比率&#xff1f; 在投資分析中&#xff0c;我們通常使用 夏普比率&#xff08;Sharpe Ratio&#xff09; 來衡量風險調整后的…

深度學習奠基作 AlexNet 論文閱讀筆記(2025.2.25)

文章目錄 訓練數據集數據預處理神經網絡模型模型訓練正則化技術模型性能其他補充 訓練數據集 模型主要使用2010年和2012年的 ImageNet 大規模視覺識別挑戰賽&#xff08;ILSVRC&#xff09;提供的 ImageNet 的子集進行訓練&#xff0c;這些子集包含120萬張圖像。最終&#xff…

Deepseek 實戰全攻略,領航科技應用的深度探索之旅

想玩轉 Deepseek&#xff1f;這攻略別錯過&#xff01;先帶你了解它的基本原理&#xff0c;教你搭建運行環境。接著給出自然語言處理、智能客服等應用場景的實操方法與代碼。還分享模型微調、優化技巧&#xff0c;結合案例加深理解&#xff0c;讓你全面掌握&#xff0c;探索科技…