大家好!今天我们来聊聊Java中的设计模式。设计模式是软件开发中的最佳实践,它们提供了解决常见问题的模板。无论是提高代码的可读性、可维护性,还是增强系统的灵活性,设计模式都扮演着重要角色。本文将深入探讨几种常见的设计模式,并通过实际代码示例帮助你理解它们的应用场景和实现方式。准备好了吗?让我们开始吧!😄


一、设计模式简介

设计模式是软件工程中经过验证的解决方案,用于解决在特定上下文中反复出现的问题。它们不是具体的代码,而是一种设计思想,可以帮助我们构建更优雅、更灵活的代码。

设计模式分为三大类:

  1. 创建型模式:关注对象的创建(如单例模式、工厂模式)。
  2. 结构型模式:关注类和对象的组合(如装饰器模式、适配器模式)。
  3. 行为型模式:关注对象之间的交互(如观察者模式、策略模式)。

二、单例模式:确保唯一实例

单例模式确保一个类只有一个实例,并提供一个全局访问点。

1. 应用场景

  • 数据库连接池。
  • 配置文件管理器。
  • 日志记录器。

2. 实现方式

懒汉式(线程不安全)
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
饿汉式(线程安全)
public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}
双重检查锁(线程安全且高效)
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;
    }
}

三、工厂模式:解耦对象的创建

工厂模式将对象的创建与使用分离,提供了一种统一的接口来创建不同类型的对象。

1. 应用场景

  • 创建复杂对象。
  • 需要根据条件创建不同的对象。

2. 实现方式

简单工厂模式
interface Product {
    void use();
}

class ProductA implements Product {
    @Override
    public void use() {
        System.out.println("使用产品A");
    }
}

class ProductB implements Product {
    @Override
    public void use() {
        System.out.println("使用产品B");
    }
}

class SimpleFactory {
    public static Product createProduct(String type) {
        if ("A".equals(type)) {
            return new ProductA();
        } else if ("B".equals(type)) {
            return new ProductB();
        }
        return null;
    }
}

public class Main {
    public static void main(String[] args) {
        Product product = SimpleFactory.createProduct("A");
        product.use();  // 输出:使用产品A
    }
}
工厂方法模式
interface Factory {
    Product createProduct();
}

class FactoryA implements Factory {
    @Override
    public Product createProduct() {
        return new ProductA();
    }
}

class FactoryB implements Factory {
    @Override
    public Product createProduct() {
        return new ProductB();
    }
}

public class Main {
    public static void main(String[] args) {
        Factory factory = new FactoryA();
        Product product = factory.createProduct();
        product.use();  // 输出:使用产品A
    }
}

四、观察者模式:实现对象间的松耦合

观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生变化时,所有依赖它的对象都会收到通知。

1. 应用场景

  • 事件驱动系统。
  • 消息订阅系统。

2. 实现方式

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

interface Observer {
    void update(String message);
}

class ConcreteObserver implements Observer {
    private String name;

    ConcreteObserver(String name) {
        this.name = name;
    }

    @Override
    public void update(String message) {
        System.out.println(name + " 收到消息:" + message);
    }
}

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

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

    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

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

public class Main {
    public static void main(String[] args) {
        Subject subject = new Subject();
        subject.addObserver(new ConcreteObserver("观察者A"));
        subject.addObserver(new ConcreteObserver("观察者B"));

        subject.notifyObservers("状态已更新!");
    }
}

五、装饰器模式:动态扩展对象功能

装饰器模式允许在不改变原有对象的情况下,动态地扩展其功能。

1. 应用场景

  • 动态添加功能。
  • 避免使用子类扩展功能。

2. 实现方式

interface Component {
    void operation();
}

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

class Decorator implements Component {
    private Component component;

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

    @Override
    public void operation() {
        component.operation();
    }
}

class ConcreteDecoratorA extends Decorator {
    ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        System.out.println("添加功能A");
    }
}

class ConcreteDecoratorB extends Decorator {
    ConcreteDecoratorB(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        System.out.println("添加功能B");
    }
}

public class Main {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        component = new ConcreteDecoratorA(component);
        component = new ConcreteDecoratorB(component);

        component.operation();
        // 输出:
        // 执行操作
        // 添加功能A
        // 添加功能B
    }
}

六、其他常见设计模式

1. 适配器模式

适配器模式将一个类的接口转换成客户端期望的另一个接口。

2. 策略模式

策略模式定义了一系列算法,并将它们封装起来,使它们可以互换。

3. 代理模式

代理模式为其他对象提供一个代理,以控制对这个对象的访问。


七、总结:设计模式让代码更优雅!

恭喜你!现在你已经掌握了Java中几种常见的设计模式,包括单例模式、工厂模式、观察者模式、装饰器模式等。设计模式是构建高质量代码的重要工具,掌握了它们,你就能编写出更优雅、更灵活的代码。

接下来,你可以尝试在实际项目中应用这些设计模式,比如用单例模式管理全局资源、用观察者模式实现事件驱动系统等。加油,未来的Java大神!🚀


PS:如果你在学习过程中遇到问题,别担心!欢迎在评论区留言,我会尽力帮你解决!😄

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐