深入剖析GOF23設計模式

一、單例模式

單例模式是一種創建型設計模式,可以保證一個類僅有一個實例,並提供了全局訪問點。

單例模式的核心是構造函數是私有的,外界無法通過構造函數來創建實例。並且提供了一個靜態方法來獲取單例對象。這樣就可以確保在整個應用中,只有一個該類的實例對象。


public class Singleton{
  private static volatile Singleton instance = null;
  private Singleton(){}
  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class) {
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}

單例模式適用於全局開關、日誌記錄、線程池等場景。

二、工廠模式

工廠模式是一種創建型設計模式,可以創建一組相關的對象,而無需指定其具體類。

工廠模式分為簡單工廠模式、工廠方法模式和抽象工廠模式。

簡單工廠模式:


public interface Animal{
  void sound();
}

public class Dog implements Animal{
  public void sound(){
     System.out.println("Dog: Bark");
  }
}

public class Cat implements Animal{
  public void sound(){
     System.out.println("Cat: Meow");
  }
}

public class AnimalFactory{
  public static Animal createAnimal(String type){
     switch(type){
        case "dog":
           return new Dog();
        case "cat":
           return new Cat();
        default:
           throw new IllegalArgumentException("Invalid animal type: " + type);
    }
  }
}

工廠方法模式:


public interface Animal{
  void sound();
}

public class Dog implements Animal{
  public void sound(){
     System.out.println("Dog: Bark");
  }
}

public class Cat implements Animal{
  public void sound(){
     System.out.println("Cat: Meow");
  }
}

public interface AnimalFactory{
  Animal createAnimal();
}

public class DogFactory implements AnimalFactory{
  public Animal createAnimal(){
    return new Dog();
  }
}

public class CatFactory implements AnimalFactory{
  public Animal createAnimal(){
    return new Cat();
  }
}

抽象工廠模式:


public interface Animal{
  void sound();
}

public class Dog implements Animal{
  public void sound(){
     System.out.println("Dog: Bark");
  }
}

public class Cat implements Animal{
  public void sound(){
     System.out.println("Cat: Meow");
  }
}

public interface AnimalFactory{
  Animal createAnimal();
}

public class DomesticAnimalFactory implements AnimalFactory{
  public Animal createAnimal(){
    return new Dog();
  }
}

public class WildAnimalFactory implements AnimalFactory{
  public Animal createAnimal(){
    return new Lion();
  }
}

工廠模式適用於創建複雜對象、創建可擴展組件的場景。

三、觀察者模式

觀察者模式是一種行為型設計模式,當對象之間存在一對多關係時,當一個對象狀態變化時,所有依賴它的對象都將得到通知。


import java.util.ArrayList;
import java.util.List;

public interface Observer{
  void update(String message);
}

public class User implements Observer{
  private String name;
  
  public User(String name){
    this.name = name;
  }
  
  public void update(String message){
    System.out.println(name + ": " + message);
  }
}

public interface Subject{
  void attach(Observer observer);
  void detach(Observer observer);
  void notifyObservers(String message);
}

public class News implements Subject{
  private List observers = new ArrayList();
  
  public void attach(Observer observer){
    observers.add(observer);
  }
  
  public void detach(Observer observer){
    observers.remove(observer);
  }
  
  public void notifyObservers(String message){
    for(Observer observer : observers){
      observer.update(message);
    }
  }
  
  public void publish(String message){
    System.out.println("Publish: " + message);
    notifyObservers("News: " + message);
  }
}

觀察者模式適用於發布訂閱模型、多個對象間解耦、動態更新

四、裝飾器模式

裝飾器模式是一種行為型設計模式,可以動態地為一個對象增加額外的職責,而無需修改它的代碼。


public interface Coffee{
  String getDescription();
  double getCost();
}

public class Espresso implements Coffee{
  public String getDescription(){
    return "Espresso";
  }
  
  public double getCost(){
    return 1.99;
  }
}

public abstract class CoffeeDecorator implements Coffee{
  protected Coffee coffee;
  
  public CoffeeDecorator(Coffee coffee){
    this.coffee = coffee;
  }
  
  public String getDescription(){
    return coffee.getDescription();
  }
  
  public double getCost(){
    return coffee.getCost();
  }
}

public class Milk extends CoffeeDecorator{
  public Milk(Coffee coffee){
    super(coffee);
  }
  
  public String getDescription(){
    return coffee.getDescription() + ", Milk";
  }
  
  public double getCost(){
    return coffee.getCost() + 0.5;
  }
}

public class Mocha extends CoffeeDecorator{
  public Mocha(Coffee coffee){
    super(coffee);
  }
  
  public String getDescription(){
    return coffee.getDescription() + ", Mocha";
  }
  
  public double getCost(){
    return coffee.getCost() + 1.0;
  }
}

裝飾器模式適用於動態地為一個對象增加額外的職責,是繼承關係的一個替代方案。

五、適配器模式

適配器模式是一種結構型設計模式,可以將一個類的接口轉換成客戶端需要的另一個接口。


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{
  public void playVlc(String fileName){
    System.out.println("Playing vlc file. Name: "+ fileName); 
  }
  public void playMp4(String fileName){}
}

public class Mp4Player implements AdvancedMediaPlayer{
  public void playVlc(String fileName){}
  public void playMp4(String fileName){
    System.out.println("Playing mp4 file. Name: "+ fileName); 
  }
}

public class MediaAdapter implements MediaPlayer{
  AdvancedMediaPlayer advancedMusicPlayer;
  
  public MediaAdapter(String audioType){
    if(audioType.equalsIgnoreCase("vlc") ){
      advancedMusicPlayer = new VlcPlayer();       
    }
    else if (audioType.equalsIgnoreCase("mp4")){
      advancedMusicPlayer = new Mp4Player();
    }
  }

  public void play(String audioType, String fileName) {
    if(audioType.equalsIgnoreCase("vlc")){
      advancedMusicPlayer.playVlc(fileName);
    }
    else if(audioType.equalsIgnoreCase("mp4")){
      advancedMusicPlayer.playMp4(fileName);
    }
  }
}

public class AudioPlayer implements MediaPlayer{
  MediaAdapter mediaAdapter; 

  public void play(String audioType, String fileName) {    
    if(audioType.equalsIgnoreCase("mp3")){
      System.out.println("Playing mp3 file. Name: " + fileName);           
    }
    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");
    }
  }
}

適配器模式適用於已有的接口無法滿足需求的場景,通過定義新的接口轉化使用。

原創文章,作者:QSYH,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/136324.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
QSYH的頭像QSYH
上一篇 2024-10-04 00:16
下一篇 2024-10-04 00:16

相關推薦

  • 手機安全模式怎麼解除?

    安全模式是一種手機自身的保護模式,它會禁用第三方應用程序並使用僅限基本系統功能。但有時候,安全模式會使你無法使用手機上的一些重要功能。如果你想解除手機安全模式,可以嘗試以下方法: …

    編程 2025-04-28
  • Qt State Machine與狀態機模式

    本文將介紹Qt State Machine和狀態機模式在Qt中的實現。Qt提供了QStateMachine和QState兩個類,可以方便地實現狀態機模式,並且能有效地處理複雜的、多…

    編程 2025-04-27
  • 顯示C++設計模式

    本文將詳細介紹顯示C++設計模式的概念、類型、優點和代碼實現。 一、概念 C++設計模式是在軟件設計階段定義,用於處理常見問題的可重用解決方案。這些解決方案是經過測試和驗證的,並已…

    編程 2025-04-27
  • Centos7進入單用戶模式的解釋

    本文將介紹如何在Centos7中進入單用戶模式,並從以下幾個方面進行詳細的闡述。 一、Centos7進入單用戶模式的解答 在Centos7中進入單用戶模式需要執行以下步驟: 1. …

    編程 2025-04-27
  • 深入解析Vue3 defineExpose

    Vue 3在開發過程中引入了新的API `defineExpose`。在以前的版本中,我們經常使用 `$attrs` 和` $listeners` 實現父組件與子組件之間的通信,但…

    編程 2025-04-25
  • 深入理解byte轉int

    一、字節與比特 在討論byte轉int之前,我們需要了解字節和比特的概念。字節是計算機存儲單位的一種,通常表示8個比特(bit),即1字節=8比特。比特是計算機中最小的數據單位,是…

    編程 2025-04-25
  • 深入理解Flutter StreamBuilder

    一、什麼是Flutter StreamBuilder? Flutter StreamBuilder是Flutter框架中的一個內置小部件,它可以監測數據流(Stream)中數據的變…

    編程 2025-04-25
  • 深入探討OpenCV版本

    OpenCV是一個用於計算機視覺應用程序的開源庫。它是由英特爾公司創建的,現已由Willow Garage管理。OpenCV旨在提供一個易於使用的計算機視覺和機器學習基礎架構,以實…

    編程 2025-04-25
  • 深入了解scala-maven-plugin

    一、簡介 Scala-maven-plugin 是一個創造和管理 Scala 項目的maven插件,它可以自動生成基本項目結構、依賴配置、Scala文件等。使用它可以使我們專註於代…

    編程 2025-04-25
  • 深入了解LaTeX的腳註(latexfootnote)

    一、基本介紹 LaTeX作為一種排版軟件,具有各種各樣的功能,其中腳註(footnote)是一個十分重要的功能之一。在LaTeX中,腳註是用命令latexfootnote來實現的。…

    編程 2025-04-25

發表回復

登錄後才能評論