深入剖析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/n/136324.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
QSYHQSYH
上一篇 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

发表回复

登录后才能评论