当前位置: 首页 > article >正文

Java常用设计模式及其应用场景

1. 什么是设计模式?

        设计模式是一个经过多次验证的、针对常见问题的可复用解决方案。设计模式并不是具体的代码实现,而是给出了如何解决问题的思路和结构。在实际开发过程中,设计模式有助于开发者快速找到合适的解决方案,从而减少重复造轮子的工作,提高开发效率。

设计模式通常用于以下方面:

  • 解决软件设计中常见的结构性问题
  • 提高代码的复用性和可维护性
  • 增强代码的灵活性,使得后期维护和扩展更加简单

2. 设计模式的分类

设计模式根据其功能和应用场景的不同,通常分为三大类:

  • 创建型模式:关注如何创建对象。
  • 结构型模式:关注如何组合类和对象以实现更大规模的功能。
  • 行为型模式:关注对象之间的交互和职责分配。

 具体示例:

  • 创建型模式:单例模式、工厂方法模式、抽象工厂模式、建造者模式、原型模式。
  • 结构型模式:适配器模式、装饰器模式、代理模式。
  • 行为型模式:观察者模式、策略模式。

3. 常用设计模式及其应用场景

1. 单例模式(Singleton Pattern)

单例模式确保一个类只有一个实例,并提供一个全局访问点。该模式通常用于管理全局状态,如日志记录、数据库连接池等。

应用场景:数据库连接池、日志类、配置类。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

2. 工厂方法模式(Factory Method Pattern)

工厂方法模式定义一个创建对象的接口,但由子类决定实例化哪个类。它将类的实例化推迟到子类。

应用场景:当你不希望具体化一个类,或者在实例化时需要很多条件判断时。

public interface Product {
    void doSomething();
}

public class ConcreteProductA implements Product {
    @Override
    public void doSomething() {
        System.out.println("Product A");
    }
}

public abstract class Creator {
    public abstract Product factoryMethod();
}

public class ConcreteCreatorA extends Creator {
    @Override
    public Product factoryMethod() {
        return new ConcreteProductA();
    }
}

3. 抽象工厂模式(Abstract Factory Pattern)

抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而无需指定具体的类。

应用场景:需要一组相关产品,但不希望产品的具体实现暴露给客户端时。

public interface AbstractFactory {
    Product createProduct();
}

public class ConcreteFactoryA implements AbstractFactory {
    @Override
    public Product createProduct() {
        return new ConcreteProductA();
    }
}

4. 建造者模式(Builder Pattern)

建造者模式将复杂对象的构建过程与表示分离,使得同样的构建过程可以创建不同的表示。

应用场景:当对象的构建过程独立于其组成部分的创建和装配时。

public class Product {
    private String partA;
    private String partB;

    public void setPartA(String partA) {
        this.partA = partA;
    }

    public void setPartB(String partB) {
        this.partB = partB;
    }
}

public class ProductBuilder {
    private Product product;

    public ProductBuilder() {
        product = new Product();
    }

    public ProductBuilder buildPartA(String partA) {
        product.setPartA(partA);
        return this;
    }

    public ProductBuilder buildPartB(String partB) {
        product.setPartB(partB);
        return this;
    }

    public Product build() {
        return product;
    }
}

5. 原型模式(Prototype Pattern)

原型模式通过复制现有的实例来创建新对象,而不是通过构造函数创建。

应用场景:对象的创建成本较高,需要通过复制已有对象来创建时。

public class Prototype implements Cloneable {
    private String name;

    public Prototype(String name) {
        this.name = name;
    }

    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (Prototype) super.clone();
    }
}

6. 适配器模式(Adapter Pattern)

适配器模式将一个类的接口转换成客户端希望的另一个接口,使得原本接口不兼容的类能够一起工作。

应用场景:当你希望在不修改代码的情况下,使接口不兼容的类可以一起工作时。

public interface Target {
    void request();
}

public class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request");
    }
}

public class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

7. 装饰器模式(Decorator Pattern)

装饰器模式允许你动态地给一个对象添加额外的功能,而不需要改变其结构。

应用场景:当需要扩展类的功能,但又不想改变类的结构时。

public interface Component {
    void operation();
}

public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("ConcreteComponent operation");
    }
}

public class Decorator implements Component {
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
        System.out.println("Decorator additional operation");
    }
}

8. 代理模式(Proxy Pattern)

代理模式为其他对象提供代理以控制对该对象的访问。

应用场景:需要对对象的访问进行控制时,如延迟加载、权限控制等。

public interface Subject {
    void request();
}

public class RealSubject implements Subject {
    @Override
    public void request() {
        System.out.println("RealSubject request");
    }
}

public class Proxy implements Subject {
    private RealSubject realSubject;

    @Override
    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        realSubject.request();
    }
}

9. 观察者模式(Observer Pattern)

观察者模式定义了一种一对多的依赖关系,使得一个对象的状态变化时,其相关依赖对象都能收到通知并自动更新。

应用场景:当一个对象的状态变化需要通知其他多个对象时。

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

public class ConcreteObserver implements Observer {
    @Override
    public void update(String message) {
        System.out.println("Received message: " + message);
    }
}

public class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

10. 策略模式(Strategy Pattern)

策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互换。策略模式让算法的变化独立于使用算法的客户。

应用场景:当有多个算法可以完成相同的任务时,可以通过策略模式选择不同的算法。

public interface Strategy {
    void execute();
}

public class ConcreteStrategyA implements Strategy {
    @Override
    public void execute() {
        System.out.println("Strategy A executed");
    }
}

public class ConcreteStrategyB implements Strategy {
    @Override
    public void execute() {
        System.out.println("Strategy B executed");
    }
}

public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void executeStrategy() {
        strategy.execute();
    }
}


http://www.kler.cn/a/556861.html

相关文章:

  • [Windows] Umi-OCR 开源批量文字识别 支持图片,文档,二维码,截图等
  • 从0-1搭建mac环境最新版
  • 常用加解密原理及实际使用
  • Vue2 和 Vue3 的区别
  • halcon激光三角测量(二十一)calibrate_sheet_of_light_calplate
  • Ubuntu24安装MongoDB(解压版)
  • 什么是向量化?ElasticSearch如何存储向量化?
  • 如何在 Vue 应用中实现权限管理?
  • 关于css中bfc的理解
  • SOME/IP--协议英文原文讲解12(完结)
  • 计算机专业知识【数据库读操作:不可重复读、脏读及其他现象解析】
  • 【接口封装】——13、登录窗口的标题栏内容设置
  • 跳跃游戏(力扣55)
  • Selenium实战案例1:论文pdf自动下载
  • 城电科技|可展开光伏花 绽放绿色 点亮未来
  • JavaScript 中,数据类型 有哪些?(复习/面试)
  • JVM系列--虚拟机类加载机制
  • TSMaster【第四篇:目击之术——总线测量窗口精解】
  • MATLAB拟合算法:如何使用 MATLAB 进行多组数据的高斯拟合分析
  • 【Kubernets】Kubernets资源类型Deployment详细介绍