(Java基礎筆記vlog)Java中常見的幾種設計模式詳解

前言:

? 在 Java 編程里,設計模式是被反復使用、多數人知曉、經過分類編目的代碼設計經驗總結。他能幫助開發者更高效地解決常見問題,提升代碼的可維護性、可擴展性和復用性。下面介紹Java 中幾種常見的設計模式。

  • 單例模式(Singleton Pattern)
  • 工廠模式(Factory Pattern)
  • 代理模式(Proxy Pattern)
  • 裝飾器模式(Decorator Pattern)
  • 觀察者模式(Observer Pattern)
  • 策略模式(Strategy Pattern)
  • 模板方法模式(Template Method Pattern)
  • 適配器模式(Adapter Pattern)
  • 責任鏈模式(Chain of Responsibility Pattern)

1.單例模式(Singleton Pattern)

核心思想:封裝化所有構造方法確保一個類只有一個實例,并提供一個全局訪問點。

示例:

public class Singleton {// 類加載時不創建實例private static volatile Singleton instance;// 私有構造函數,防止外部實例化private Singleton() {}// 提供全局訪問點,使用雙重檢查鎖定機制保證線程安全public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;}
}

2.工廠模式(Factory Pattern)

核心思想:他通過封裝對象的創建邏輯,實現了對象創建和使用的分離,提高了代碼的可維護性和可擴展性。

示例:

// 接口
interface Shape {void draw();
}// 實現類
class Circle implements Shape {@Overridepublic void draw() {System.out.println("畫一個圓形");}
}class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("畫一個矩形");}
}// 工廠類
class ShapeFactory {public Shape getShape(String shapeType) {if (shapeType == null) {return null;}if (shapeType.equalsIgnoreCase("CIRCLE")) {return new Circle();} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {return new Rectangle();}return null;}
}

3.代理模式(Proxy Pattern)

核心思想:為其他對象提供一種代理以控制對這個對象的訪問。

示例:

// 抽象主題接口
public interface Subject {void request();
}// 真實主題類
public class RealSubject implements Subject {@Overridepublic void request() {System.out.println("RealSubject request");}
}// 代理類
public class Proxy implements Subject {private RealSubject realSubject;@Overridepublic void request() {if (realSubject == null) {realSubject = new RealSubject();}realSubject.request();  // 代理控制對真實主題的訪問}
}// 客戶端代碼
public class Client {public static void main(String[] args) {Subject proxy = new Proxy();proxy.request();  // 通過代理訪問真實主題}
}

4.裝飾器模式(Decorator Pattern)

核心思想:裝飾器模式動態地給一個對象添加一些額外的職責。

示例:

// 接口
interface Coffee {double getCost();String getDescription();
}// 基礎實現
class SimpleCoffee implements Coffee {@Overridepublic double getCost() {return 1.0;}@Overridepublic String getDescription() {return "簡單咖啡";}
}// 裝飾器抽象類
abstract class CoffeeDecorator implements Coffee {protected Coffee decoratedCoffee;public CoffeeDecorator(Coffee decoratedCoffee) {this.decoratedCoffee = decoratedCoffee;}@Overridepublic double getCost() {return decoratedCoffee.getCost();}@Overridepublic String getDescription() {return decoratedCoffee.getDescription();}
}// 具體裝飾器
class Milk extends CoffeeDecorator {public Milk(Coffee decoratedCoffee) {super(decoratedCoffee);}@Overridepublic double getCost() {return decoratedCoffee.getCost() + 0.5;}@Overridepublic String getDescription() {return decoratedCoffee.getDescription() + ", 加牛奶";}
}

5.觀察者模式(Observer Pattern)

核心思想:觀察者模式定義對象間的一種一對多的依賴關系,當一個對象的狀態發生改變時,所有依賴它的對象都會得到通知并被自動更新。

示例:

import java.util.ArrayList;
import java.util.List;// 主題接口
interface Subject {void registerObserver(Observer o);void removeObserver(Observer o);void notifyObservers();
}// 觀察者接口
interface Observer {void update(double temperature, double humidity, double pressure);
}// 具體主題
class WeatherData implements Subject {private List<Observer> observers;private double temperature;private double humidity;private double pressure;public WeatherData() {observers = new ArrayList<>();}@Overridepublic void registerObserver(Observer o) {observers.add(o);}@Overridepublic void removeObserver(Observer o) {observers.remove(o);}@Overridepublic void notifyObservers() {for (Observer observer : observers) {observer.update(temperature, humidity, pressure);}}public void measurementsChanged() {notifyObservers();}public void setMeasurements(double temperature, double humidity, double pressure) {this.temperature = temperature;this.humidity = humidity;this.pressure = pressure;measurementsChanged();}
}

6.策略模式(Strategy Pattern)

核心思想:策略模式定義一系列的算法,并將每個算法封裝起來,使他們可以相互替換。

示例:

// 策略接口
interface PaymentStrategy {void pay(int amount);
}// 具體策略
class CreditCardStrategy implements PaymentStrategy {private String cardNumber;private String cvv;private String dateOfExpiry;public CreditCardStrategy(String cardNumber, String cvv, String dateOfExpiry) {this.cardNumber = cardNumber;this.cvv = cvv;this.dateOfExpiry = dateOfExpiry;}@Overridepublic void pay(int amount) {System.out.println(amount + " 元使用信用卡支付");}
}class PayPalStrategy implements PaymentStrategy {private String emailId;private String password;public PayPalStrategy(String emailId, String password) {this.emailId = emailId;this.password = password;}@Overridepublic void pay(int amount) {System.out.println(amount + " 元使用PayPal支付");}
}// 上下文
class ShoppingCart {private PaymentStrategy paymentStrategy;public void setPaymentStrategy(PaymentStrategy paymentStrategy) {this.paymentStrategy = paymentStrategy;}public void pay(int amount) {paymentStrategy.pay(amount);}
}

7.模板方法模式(Template Method Pattern)

核心思想:模板方法模式定義一個操作中的算法的骨架,而將一些步驟延遲到子類中。

示例:

// 抽象類
abstract class Game {abstract void initialize();abstract void startPlay();abstract void endPlay();// 模板方法public final void play() {// 初始化游戲initialize();// 開始游戲startPlay();// 結束游戲endPlay();}
}// 具體類
class Cricket extends Game {@Overridevoid initialize() {System.out.println("板球游戲初始化,準備場地");}@Overridevoid startPlay() {System.out.println("板球游戲開始,玩起來!");}@Overridevoid endPlay() {System.out.println("板球游戲結束,統計分數");}
}class Football extends Game {@Overridevoid initialize() {System.out.println("足球游戲初始化,準備場地和球");}@Overridevoid startPlay() {System.out.println("足球游戲開始,踢起來!");}@Overridevoid endPlay() {System.out.println("足球游戲結束,統計分數");}
}

8.適配器模式(Adapter Pattern)

核心思想:適配器模式將一個類的接口轉換成客戶希望的另外一個接口。

示例:

// 目標接口
interface MediaPlayer {void play(String audioType, String fileName);
}// 被適配的類
class VlcPlayer {public void playVlc(String fileName) {System.out.println("播放VLC文件: " + fileName);}
}// 適配器
class MediaAdapter implements MediaPlayer {private VlcPlayer vlcPlayer;public MediaAdapter() {vlcPlayer = new VlcPlayer();}@Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase("vlc")) {vlcPlayer.playVlc(fileName);}}
}// 具體實現類
class AudioPlayer implements MediaPlayer {private MediaAdapter mediaAdapter;@Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase("vlc")) {mediaAdapter = new MediaAdapter();mediaAdapter.play(audioType, fileName);} else {System.out.println("播放 " + audioType + " 文件: " + fileName);}}
}

9.責任鏈模式(Chain of Responsibility Pattern)

核心思想:責任鏈模式為請求創建了一個接收者對象的鏈,每個接收者都包含對另一個接收者的引用。

示例:

// 抽象處理者
abstract class Handler {protected Handler nextHandler;public void setNextHandler(Handler nextHandler) {this.nextHandler = nextHandler;}public abstract void handleRequest(int request);
}// 具體處理者
class ConcreteHandler1 extends Handler {@Overridepublic void handleRequest(int request) {if (request < 10) {System.out.println("處理請求: " + request);} else if (nextHandler != null) {nextHandler.handleRequest(request);}}
}class ConcreteHandler2 extends Handler {@Overridepublic void handleRequest(int request) {if (request >= 10 && request < 20) {System.out.println("處理請求: " + request);} else if (nextHandler != null) {nextHandler.handleRequest(request);}}
}class ConcreteHandler3 extends Handler {@Overridepublic void handleRequest(int request) {if (request >= 20) {System.out.println("處理請求: " + request);} else if (nextHandler != null) {nextHandler.handleRequest(request);}}
}

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

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

相關文章

(8)Spring Boot 原生鏡像支持

Spring Boot 原生鏡像支持 ?? 點擊展開題目 在Spring Boot 3.x中,如何設計一個支持GraalVM原生鏡像的微服務?需要特別注意哪些限制? ?? Spring Boot 3.x 原生鏡像概述 Spring Boot 3.x 通過 Spring Native 項目提供了對 GraalVM 原生鏡像的一流支持,使開發者能夠將 S…

不使用SOAP,從PDF表單連接數據庫

不使用SOAP協議&#xff0c;通過XFDF格式實現PDF表單與數據庫交互的方法。該方法兼容免費的Adobe Reader&#xff0c;且無需特殊權限設置。 背景與問題 歷史方案: Adobe曾提供ADBC接口&#xff08;基于ODBC&#xff09;&#xff0c;但在Acrobat 9后被移除。SOAP方案在免費版Rea…

HTTP由淺入深

文章目錄 概述特點URL HTTP 與 HTTPS概述HTTP 工作原理HTTPS 的作用區別總結 請求報文請求行常見請求方法請求頭請求體Content-Type 詳解常見場景 Content-Type 對應關系 響應報文響應行狀態碼詳解1xx&#xff1a;信息響應&#xff08;Informational&#xff09;2xx&#xff1a…

Redis淘汰策略

Redis有八種淘汰策略 noeviction &#xff1a;不進行淘汰&#xff0c;直接報錯。allkeys-lru &#xff1a;隨機淘汰最久未使用的鍵。volatile-lru &#xff1a;從設置了過期時間的鍵中&#xff0c;隨機淘汰最久未使用的鍵。allkeys-random &#xff1a;隨機淘汰某個鍵。volati…

Maven打包SpringBoot項目,因包含SpringBootTest單元測試和Java預覽版特性導致打包失敗

SpringBoot啟用Java預覽版特性&#xff08;無測試類&#xff09; 在pom.xml文件中加入以下配置表示啟用Java預覽版 <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration>…

Makefile快速入門

簡介?&#xff1a; ? Makefile? 是一種用于自動化構建和管理軟件項目的工具文件&#xff0c;通常與 make 命令配合使用。它通過定義?規則?&#xff08;rules&#xff09;來指定如何從源文件生成目標文件&#xff08;如可執行程序或庫&#xff09;&#xff0c;并自動…

RISC-V 開發板 MUSE Pi Pro OpenCV結合Gstreamer實時顯示CSI攝像頭

視頻講解&#xff1a;RISC-V 開發板 MUSE Pi Pro OpenCV結合Gstreamer實時顯示CSI攝像頭_嗶哩嗶哩_bilibili RISC-V 開發板 MUSE Pi Pro OpenCV結合Gstreamer實時顯示CSI攝像頭 安裝opencv相關庫 sudo apt install libopencv-dev python3 python3-opencv 測試使用的CSI攝像頭…

如何用JAVA手寫一個Tomcat

一、初步理解Tomcat Tomcat是什么&#xff1f; Tomcat 是一個開源的 輕量級 Java Web 應用服務器&#xff0c;核心功能是 運行 Servlet/JSP。 Tomcat的核心功能&#xff1f; Servlet 容器&#xff1a;負責加載、實例化、調用和銷毀 Servlet。 HTTP 服務器&#xff1a;監聽端口…

短劇系統開發與抖音生態融合:短視頻時代的新風口與商業機遇

在短視頻內容井噴的時代&#xff0c;“短劇”作為一種新興內容形態&#xff0c;正以驚人的速度搶占用戶注意力。抖音、快手等平臺日均播放量破億的短劇作品&#xff0c;不僅催生了新的內容創作風口&#xff0c;更推動了短劇系統開發的巨大市場需求。本文將深度解析短劇系統開發…

《云原生安全攻防》-- K8s日志審計:從攻擊溯源到安全實時告警

當K8s集群遭受入侵時&#xff0c;安全管理員可以通過審計日志進行攻擊溯源&#xff0c;通過分析攻擊痕跡&#xff0c;我們可以找到攻擊者的入侵行為&#xff0c;還原攻擊者的攻擊路徑&#xff0c;以便修復安全問題。 在本節課程中&#xff0c;我們將介紹如何配置K8s審計日志&am…

3dczml時間動態圖型場景

在cesium中我們了可以使用czml數據來生成可以隨時間變化而變化的物體. 首先導入czml數據 設置時間范圍 id: "point" //物體在什么時間范圍可用 availability:"2012-08-04T16:00:00Z/2012-08-04T16:05:00Z"position:{ //設置物體的起始時間 epoch:"…

超小多模態視覺語言模型MiniMind-V 訓練

簡述 MiniMind-V 是一個超適合初學者的項目&#xff0c;讓你用普通電腦就能訓一個能看圖說話的 AI。訓練過程就像教小孩&#xff1a;先準備好圖文材料&#xff08;數據集&#xff09;&#xff0c;教它基礎知識&#xff08;預訓練&#xff09;&#xff0c;再教具體技能&#xf…

01-jenkins學習之旅-window-下載-安裝-安裝后設置向導

1 jenkins簡介 百度百科介紹&#xff1a;Jenkins是一個開源軟件項目&#xff0c;是基于Java開發的一種持續集成工具&#xff0c;用于監控持續重復的工作&#xff0c;旨在提供一個開放易用的軟件平臺&#xff0c;使軟件項目可以進行持續集成。 [1] Jenkins官網地址 翻譯&…

VPLC (VPLCnext) K8S

前序 在接觸Virtual PLCnext Control的時候&#xff0c;我想過好幾次如何將它運行在k8s上&#xff0c;由于對k8s的熟悉程度不夠&#xff0c;跌跌撞撞嘗試了很久&#xff0c;終于把vPLC部署在單機版的k8s上了。&#xff08;此教程僅為demo階段&#xff0c;此教程僅為demo階段&a…

OPC Client第5講(wxwidgets):初始界面的事件處理;按照配置文件初始化界面的內容

接上一講&#xff0c;即實現下述界面的事件處理代碼&#xff1b;并且按照配置文件初始化界面的內容&#xff08;三、&#xff09; 事件處理的基礎知識&#xff0c;見下述鏈接五、 OPC Client第3講&#xff08;wxwidgets&#xff09;&#xff1a;wxFormBuilder&#xff1b;基礎…

從乳制品行業轉型看智能化升級新機遇——兼談R2AIN SUITE的賦能實踐

一、市場現狀&#xff1a;乳制品行業迎來智能化轉型關鍵期 中國乳制品行業在經歷高速增長與深度調整后&#xff0c;已進入以"安全、效率、創新"為核心的新發展階段。根據施耐德電氣白皮書數據顯示&#xff0c;2019年乳制品合格率達99.8%[1]&#xff0c;液態奶占據77…

[20250522]目前市場上主流AI開發板及算法盒子的芯片配置、架構及支持的AI推理框架的詳細梳理

目前市場上主流AI開發板及算法盒子的芯片配置、架構及支持的AI推理框架的詳細梳理

【Golang筆記03】error、panic、fatal錯誤處理學習筆記

Golang筆記&#xff1a;錯誤處理學習筆記 一、進階學習 1.1、錯誤&#xff08;異常處理&#xff09; Go語言中也有和Java中的異常處理相關的機制&#xff0c;不過&#xff0c;在Go里面不叫異常&#xff0c;而是叫做&#xff1a;錯誤。錯誤分為三類&#xff0c;分別是&#x…

Python可視化設計原則

在數據驅動的時代&#xff0c;可視化不僅是結果的呈現方式&#xff0c;更是數據故事的核心載體。Python憑借其豐富的生態庫&#xff08;Matplotlib/Seaborn/Plotly等&#xff09;&#xff0c;已成為數據可視化領域的主力工具。但工具只是起點&#xff0c;真正讓圖表產生價值的&…

??WPF入門與XAML基礎:從零開始構建你的第一個WPF應用?

從零開始構建你的第一個WPF應用? 1.什么是WPF&#xff1f;??2.開發環境搭建??2.1 安裝Visual Studio??2.2 創建第一個WPF項目?? 3. WPF項目結構解析????3.1 MainWindow.xaml??3.2 MainWindow.xaml.cs?? 4. XAML基礎語法??4.1 屬性賦值方式??4.2 命名空間&…