Java設計模式

🙈作者簡介:練習時長兩年半的Java up主
🙉個人主頁:程序員老茶
🙊 ps:點贊👍是免費的,卻可以讓寫博客的作者開心好久好久😎
📚系列專欄:Java全棧,計算機系列(火速更新中)
💭 格言:種一棵樹最好的時間是十年前,其次是現在
🏡動動小手,點個關注不迷路,感謝寶子們一鍵三連

目錄

  • 課程名:Java
    • 內容/作用:知識點/設計/實驗/作業/練習
    • 學習:Java設計模式
    • Java設計模式
      • 1. 創建型模式
        • 1.1 簡單工廠模式(Simple Factory Pattern)
        • 1.2 工廠方法模式(Factory Method Pattern)
        • 1.3 抽象工廠模式(Abstract Factory Pattern)
      • 2. 結構型模式
        • 2.1 適配器模式(Adapter Pattern)
        • 2.2 裝飾器模式(Decorator Pattern)
      • 3. 行為型模式
        • 3.1 觀察者模式(Observer Pattern)
        • 3.2 策略模式(Strategy Pattern)

課程名:Java

內容/作用:知識點/設計/實驗/作業/練習

學習:Java設計模式

Java設計模式

1. 創建型模式

1.1 簡單工廠模式(Simple Factory Pattern)

簡單工廠模式通過一個工廠類來創建對象,根據不同的參數返回不同類的實例。

示例代碼:

public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a circle");}
}public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a rectangle");}
}public class ShapeFactory {public static Shape createShape(String shapeType) {if (shapeType.equalsIgnoreCase("circle")) {return new Circle();} else if (shapeType.equalsIgnoreCase("rectangle")) {return new Rectangle();}return null;}
}public class Main {public static void main(String[] args) {Shape circle = ShapeFactory.createShape("circle");circle.draw();Shape rectangle = ShapeFactory.createShape("rectangle");rectangle.draw();}
}
1.2 工廠方法模式(Factory Method Pattern)

工廠方法模式定義了一個創建對象的接口,但由子類決定要實例化的類是哪一個。

示例代碼:

public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a circle");}
}public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a rectangle");}
}public interface ShapeFactory {Shape createShape();
}public class CircleFactory implements ShapeFactory {@Overridepublic Shape createShape() {return new Circle();}
}public class RectangleFactory implements ShapeFactory {@Overridepublic Shape createShape() {return new Rectangle();}
}public class Main {public static void main(String[] args) {ShapeFactory circleFactory = new CircleFactory();Shape circle = circleFactory.createShape();circle.draw();ShapeFactory rectangleFactory = new RectangleFactory();Shape rectangle = rectangleFactory.createShape();rectangle.draw();}
}
1.3 抽象工廠模式(Abstract Factory Pattern)

抽象工廠模式提供一個創建一系列相關或相互依賴對象的接口,而無需指定它們具體的類。

示例代碼:

public interface Color {void fill();
}public class Red implements Color {@Overridepublic void fill() {System.out.println("Filling with red color");}
}public class Blue implements Color {@Overridepublic void fill() {System.out.println("Filling with blue color");}
}public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a circle");}
}public class Rectangle implements Shape {@Overridepublic void draw() {System.out.println("Drawing a rectangle");}
}public interface AbstractFactory {Color createColor();Shape createShape();
}public class RedCircleFactory implements AbstractFactory {@Overridepublic Color createColor() {return new Red();}@Overridepublic Shape createShape() {return new Circle();}
}public class BlueRectangleFactory implements AbstractFactory {@Overridepublic Color createColor() {return new Blue();}@Overridepublic Shape createShape() {return new Rectangle();}
}public class Main {public static void main(String[] args) {AbstractFactory redCircleFactory = new RedCircleFactory();Color red = redCircleFactory.createColor();red.fill();Shape circle = redCircleFactory.createShape();circle.draw();AbstractFactory blueRectangleFactory = new BlueRectangleFactory();Color blue = blueRectangleFactory.createColor();blue.fill();Shape rectangle = blueRectangleFactory.createShape();rectangle.draw();}
}

2. 結構型模式

2.1 適配器模式(Adapter Pattern)

適配器模式將一個類的接口轉換為客戶端所期望的另一個接口。它可以讓原本不兼容的類合作無間。

示例代碼:

public interface MediaPlayer {void play(String audioType, String fileName);
}public interface AdvancedMediaPlayer {void playVlc(String fileName);void playMp4(String fileName);
}public class VlcPlayer implements AdvancedMediaPlayer {@Overridepublic void playVlc(String fileName) {System.out.println("Playing vlc file: " + fileName);}@Overridepublic void playMp4(String fileName) {// Do nothing}
}public class Mp4Player implements AdvancedMediaPlayer {@Overridepublic void playVlc(String fileName) {// Do nothing}@Overridepublic void playMp4(String fileName) {System.out.println("Playing mp4 file: " + fileName);}
}public class MediaAdapter implements MediaPlayer {private AdvancedMediaPlayer advancedMediaPlayer;public MediaAdapter(String audioType) {if (audioType.equalsIgnoreCase("vlc")) {advancedMediaPlayer = new VlcPlayer();} else if (audioType.equalsIgnoreCase("mp4")) {advancedMediaPlayer = new Mp4Player();}}@Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase("vlc")) {advancedMediaPlayer.playVlc(fileName);} else if (audioType.equalsIgnoreCase("mp4")) {advancedMediaPlayer.playMp4(fileName);}}
}public class AudioPlayer implements MediaPlayer {private MediaAdapter mediaAdapter;@Overridepublic void play(String audioType, String fileName) {// 播放 mp3 音樂文件的內置支持if (audioType.equalsIgnoreCase("mp3")) {System.out.println("Playing mp3 file: " + fileName);}// 使用 MediaAdapter 來播放其他文件格式的音樂文件else if (audioType.equalsIgnoreCase("vlc")|| audioType.equalsIgnoreCase("mp4")) {mediaAdapter = new MediaAdapter(audioType);mediaAdapter.play(audioType, fileName);}else {System.out.println("Invalid media. " + audioType + " format not supported");}}
}public class Main {public static void main(String[] args) {MediaPlayer audioPlayer = new AudioPlayer();audioPlayer.play("mp3", "song.mp3");audioPlayer.play("vlc", "movie.vlc");audioPlayer.play("mp4", "video.mp4");audioPlayer.play("avi", "movie.avi");}
}
2.2 裝飾器模式(Decorator Pattern)

裝飾器模式動態地給一個對象添加一些額外的職責,同時又不改變其結構。

示例代碼:

public interface Car {void assemble();
}public class BasicCar implements Car {@Overridepublic void assemble() {System.out.println("Basic Car.");}
}public abstract class CarDecorator implements Car {protected Car decoratedCar;public CarDecorator(Car decoratedCar){this.decoratedCar = decoratedCar;}public void assemble(){decoratedCar.assemble();}
}public class SportsCar extends CarDecorator {public SportsCar(Car decoratedCar) {super(decoratedCar);}@Overridepublic void assemble(){super.assemble();System.out.println("Adding features of Sports Car.");}
}public class LuxuryCar extends CarDecorator {public LuxuryCar(Car decoratedCar) {super(decoratedCar);}@Overridepublic void assemble(){super.assemble();System.out.println("Adding features of Luxury Car.");}
}public class Main {public static void main(String[] args) {Car basicCar = new BasicCar();Car sportsCar = new SportsCar(basicCar);sportsCar.assemble();Car luxurySportsCar = new LuxuryCar(new SportsCar(basicCar));luxurySportsCar.assemble();}
}

3. 行為型模式

3.1 觀察者模式(Observer Pattern)

觀察者模式定義了對象之間的一對多依賴關系,當一個對象狀態發生改變時,其相關依賴對象都會收到通知并自動更新。

示例代碼:

import java.util.ArrayList;
import java.util.List;interface Observer {void update(String message);
}class User implements Observer {private final String name;User(String name) {this.name = name;}@Overridepublic void update(String message) {System.out.println(name + " received message: " + message);}
}interface Subject {void registerObserver(Observer observer);void removeObserver(Observer observer);void notifyObservers(String message);
}class NewsAgency implements Subject {private final List<Observer> observers;private String news;NewsAgency() {this.observers = new ArrayList<>();}@Overridepublic void registerObserver(Observer observer) {observers.add(observer);}@Overridepublic void removeObserver(Observer observer) {observers.remove(observer);}@Overridepublic void notifyObservers(String message) {for (Observer observer : observers) {observer.update(message);}}public void setNews(String news) {this.news = news;notifyObservers(news);}
}class Main {public static void main(String[] args) {NewsAgency newsAgency = new NewsAgency();User user1 = new User("User 1");User user2 = new User("User 2");newsAgency.registerObserver(user1);newsAgency.registerObserver(user2);newsAgency.setNews("Breaking news!");newsAgency.removeObserver(user2);newsAgency.setNews("Important news!");}
}
3.2 策略模式(Strategy Pattern)

策略模式定義了一系列算法,將每個算法封裝起來,使它們可以互相替換,使得算法可以獨立于使用它的客戶端而變化。

示例代碼:

interface PaymentStrategy {void pay(double amount);
}class CreditCardStrategy implements PaymentStrategy {private final String name;private final String cardNumber;private final String cvv;private final String dateOfExpiry;CreditCardStrategy(String name, String cardNumber, String cvv, String dateOfExpiry) {this.name = name;this.cardNumber = cardNumber;this.cvv = cvv;this.dateOfExpiry = dateOfExpiry;}@Overridepublic void pay(double amount) {System.out.println(amount + " paid with credit/debit card");}
}class PayPalStrategy implements PaymentStrategy {private final String emailId;private final String password;PayPalStrategy(String emailId, String password) {this.emailId = emailId;this.password = password;}@Overridepublic void pay(double amount) {System.out.println(amount + " paid using PayPal.");}
}class ShoppingCart {private final List<Item> items;ShoppingCart() {this.items = new ArrayList<>();}void addItem(Item item) {items.add(item);}double calculateTotal() {double total = 0;for (Item item : items) {total += item.getPrice();}return total;}void pay(PaymentStrategy paymentStrategy) {double amount = calculateTotal();paymentStrategy.pay(amount);}
}class Item {private final String name;private final double price;Item(String name, double price) {this.name = name;this.price = price;}double getPrice() {return price;}
}class Main {public static void main(String[] args) {ShoppingCart cart = new ShoppingCart();Item item1 = new Item("Item 1", 20);Item item2 = new Item("Item 2", 30);cart.addItem(item1);cart.addItem(item2);cart.pay(new CreditCardStrategy("John Doe", "1234567890123456", "123", "12/2025"));cart.pay(new PayPalStrategy("john.doe@example.com", "password"));}
}

以上是一些常見的Java設計模式,每種設計模式都有不同的應用場景和用途。使用這些設計模式可以提高代碼的可維護性、可擴展性和重用性。

往期專欄
Java全棧開發
數據結構與算法
計算機組成原理
操作系統
數據庫系統
物聯網控制原理與技術

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

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

相關文章

新材料制造ERP用哪個好?企業應當如何挑選適用的

有些新材料存在特殊性&#xff0c;并且在制造過程中對車間、設備、工藝、人員等方面提出更高的要求。還有些新材料加工流程復雜&#xff0c;涉及多種材料的請購、出入庫、使用和管理等環節&#xff0c;解決各個業務環節無縫銜接問題是很多制造企業面臨的管理難題。 新材料制造…

牙科診所小程序開發案例

一、背景&#xff1a; 針對傳統口腔醫療領域中口腔診所推廣難,紙質信息保存難等問題&#xff0c;設計并開發了基于微信小程序實現口腔服務助手平臺。為了給人們提供便捷&#xff0c;快速的預約方式&#xff0c;提高社會人群對口腔健康的關注力度。通過微信小程序互聯網技術&…

文旅虛擬人IP:數字時代的傳統文化推薦官

近幾年&#xff0c;隨著文旅虛擬人頻“上崗”&#xff0c;虛擬人逐漸成為了文旅品牌的一種新穎的傳統文化傳播思路。 文旅品牌定制化推出虛擬人&#xff0c;本質原因是2023旅游業全面復蘇&#xff0c;各文旅玩法同質化現象嚴重&#xff0c;在這樣的境遇下&#xff0c;文旅品牌開…

OpenMLDB v0.8.4 診斷工具全面升級

新的v0.8.4版本中&#xff0c;我們對于診斷工具進行了全面系統化的升級&#xff0c;以提供更加完整和智能化的診斷報告&#xff0c;有助于高效排查 OpenMLDB 集群問題&#xff0c;大幅提升運維效率。 相比于之前的版本&#xff0c;新的診斷工具增添一鍵診斷功能&#xff0c;使…

首個央企量子云計算項目,中標!

6月29日&#xff0c;北京玻色量子科技有限公司&#xff08;簡稱“玻色量子”&#xff09;成功中標中國移動云能力中心“2023—2024年量子算法及光量子算力接入關鍵技術研究項目”&#xff0c;這是玻色量子繼與移動云簽訂“五岳量子云計算創新加速計劃”后&#x1f517;&#xf…

角色管理--體驗產品專家崗

研發組織管理--角色管理--體驗產品專家崗 定位 產品用戶代言人&#xff0c;產品體驗守門員&#xff0c;保證用戶體驗感知不低于行業水平并嘗試新體驗&#xff1b; 所需資質 對產品交互有自己的心得&#xff0c;可通過設計工具直觀表達觀點能站在用戶角度思考問題&#xff0c…

揭秘 systemd:釋放 Linux 服務管理的力量【systemd 一】

&#x1f38f;&#xff1a;你只管努力&#xff0c;剩下的交給時間 &#x1f3e0; &#xff1a;小破站 揭秘 systemd&#xff1a;釋放 Linux 服務管理的力量【systemd 一】 前言第一&#xff1a;systemd簡介第二&#xff1a;核心概念解析第三&#xff1a;服務管理與啟動過程第四…

bootstrap插件的基本使用

1.更新表格數據&#xff08;根據行索引&#xff1a;僅更新一個單元格&#xff09; var rows {index : index, //更新列所在行的索引field : "status", //要更新列的fieldvalue : "正常" //要更新列的數據 } $(#table_Id).bootstrapTable("updateCel…

DELPHI開發APP回憶錄二安卓與pc端路徑的選擇

路徑方法WinAndroidGetHomePathC:\Users\ggggcexx\AppData\Roaming/data/user/0/com.stella.scan/files/GetDocumentsPathC:\Users\ggggcexx\Documents/data/user/0/com.embarcadero.FirstAidExpert_FMX_D11/filesGetSharedDocumentsPathC:\Users\Public\Documents/storage/emu…

杰發科技AC7801——EEP內存分布情況

簡介 按照文檔進行配置 核心代碼如下 /*!* file sweeprom_demo.c** brief This file provides sweeprom demo test function.**//* Includes */ #include <stdlib.h> #include "ac780x_sweeprom.h" #include "ac780x_debugout.h"/* Define …

導出文件到指定路徑??

需求&#xff1a;點擊導出pdf按鈕&#xff0c;彈出系統文件夾彈框&#xff0c;可以選擇保存文件的位置。 經查詢window.showSaveFilePicker可實現&#xff0c;但這個api處于實驗階段&#xff0c;且用下來確實和瀏覽器類型、瀏覽器版本、以及本身api就不穩定有關系。 代碼見下…

Python,FastAPI,mLB網關,無法訪問/docs

根源就是js和ccs文件訪問路由的問題&#xff0c;首先你要有本地的文件&#xff0c;詳情看https://qq742971636.blog.csdn.net/article/details/134587010。 其次&#xff0c;你需要這么寫&#xff1a; /unicontorlblip就是我配置的mLB網關路由。 app FastAPI(titleoutpaint…

【力扣:421,2935】數組內最大異或對問題

思路&#xff1a;從最高位向低位構造&#xff0c;對每一位利用哈希表尋找是否存在可使此位為1的數 第一輪找1&#xff1a;清空哈希表&#xff0c;1&#xff0c;2存1&#xff0c;到3發現1^01&#xff0c;res|1<<3 第二輪找11&#xff1a;清空哈希表&#xff0c;1存10&…

如何開發洗鞋店用的小程序

隨著人們生活水平的提高&#xff0c;洗護行業是越來越細分化了&#xff0c;從最開始的干洗店包含洗護行業的所有服務到現在有專門為洗鞋開的店&#xff0c;如果開發一款洗鞋店用的小程序&#xff0c;可以實現用戶在家下單直接有人上門取鞋的話&#xff0c;應該如何去開發呢&…

將 Spring 微服務與 BI 工具集成:最佳實踐

軟件開發領域是一個不斷發展的領域&#xff0c;新的范式和技術不斷涌現。其中&#xff0c;微服務架構和商業智能&#xff08;BI&#xff09;工具的采用是兩項關鍵進步。隨著 Spring Boot 和 Spring Cloud 在構建強大的微服務方面的普及&#xff0c;了解這些微服務如何與 BI 工具…

11-@Transaction與AOP沖突解決

如題&#xff0c;最近碰到了一個問題&#xff0c;在public方法上添加Transaction沒有生效&#xff0c;事務沒有回滾。 我自己模擬了一個功能&#xff0c;向數據庫表User里面插入用戶數據。說一下代碼背景&#xff0c; 數據庫MySQL&#xff0c;持久化層Mybatis&#xff0c;項目使…

Vue3(setup)中使用vue-cropper圖片上傳裁剪插件,復制代碼直接使用

最近在項目中用到上傳裁剪&#xff0c;看了一下代碼&#xff0c;覺得這插件可可以。梳理了一下代碼分享給大家 前端UI組件element-plus 如果你也用到了 &#xff0c;快速幫你解決了問題,別忘記點贊收藏 1.首先看效果圖 因為版本vue-cropper 眾多 &#xff0c;雖然網上有各…

阿里云windwos 安裝oracle數據庫,外部用工具連接不上,只能在服務器本機通過127.0.0.1 連接

1. 首先檢查阿里云服務器安全組端口是否開放 oracle 數據庫端口 2. 其次找到oracle 安裝的目錄&#xff0c;打開這倆個文件&#xff0c;將localhost 修改為 服務器本機名稱 3.重啟oracle 監聽服務&#xff0c;就可以連接了

ModuleNotFoundError: No module named ‘Tkinter‘

ModuleNotFoundError: No module named ‘Tkinter’ Windows 不要用 import tkinter 用from tkinter import * from tkinter import * root Tk() w Label(root, text"Hello, world!") w.pack() root.mainloop()mac python 3.10版本 brew install python-tk3.1…

技術部工作職能規劃分析

前言 技術部的職能。以下是一個基本的框架,其中涵蓋了技術部在公司中的關鍵職能和子職能。 主要職能 技術部門的主要職能分為以下幾個板塊: - 技術規劃與戰略: 制定技術規劃和戰略,與業務團隊合作確定技術需求。 研究和預測技術趨勢,引領公司在技術創新和數字化轉型方…