Java 常用设计模式实战示例

2025-04-19设计模式3 分钟138 次阅读
AI 摘要salmon-ai

本文详细解析了 Java 中五个常用设计模式的实战用法,包括单例、策略、

前言

在日常开发中,良好的代码设计可以显著提高系统的可维护性和扩展性。设计模式作为一种经过验证的架构解决方案,帮助开发者以标准化、优雅的方式解决常见问题。本文通过五个经典设计模式(单例、策略、责任链、工厂、代理),结合 Java 实战代码进行演示,便于读者理解与应用。

一、单例模式(Singleton Pattern)

模式介绍

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

使用场景

  • 全局配置对象
  • 缓存池
  • 日志工具类等

示例代码

java 复制代码
public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }

    public void doSomething() {
        System.out.println("单例执行任务");
    }
}

测试

java 复制代码
public class Main {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2); // true
    }
}

二、策略模式(Strategy Pattern)

模式介绍

定义一系列算法,并使它们可互换,策略模式让算法独立于使用它的客户而变化。

使用场景

  • 多种支付方式
  • 排序策略、压缩算法等

示例代码

java 复制代码
interface PaymentStrategy {
    void pay(int amount);
}

class WeChatPay implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("使用微信支付:" + amount + " 元");
    }
}

class AliPay implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("使用支付宝支付:" + amount + " 元");
    }
}

class PaymentContext {
    private PaymentStrategy strategy;

    public PaymentContext(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void execute(int amount) {
        strategy.pay(amount);
    }
}

测试

java 复制代码
public class Main {
    public static void main(String[] args) {
        PaymentContext ctx = new PaymentContext(new WeChatPay());
        ctx.execute(100);

        ctx = new PaymentContext(new AliPay());
        ctx.execute(200);
    }
}

三、责任链模式(Chain of Responsibility)

模式介绍

多个对象依次处理请求,避免请求发送者与接收者耦合。

使用场景

  • 审批流程
  • 过滤器链

示例代码

java 复制代码
abstract class Handler {
    protected Handler next;

    public Handler setNext(Handler next) {
        this.next = next;
        return next;
    }

    public abstract void handleRequest(int level);
}

class Level1Handler extends Handler {
    public void handleRequest(int level) {
        if (level <= 1) {
            System.out.println("Level1Handler 处理请求");
        } else if (next != null) {
            next.handleRequest(level);
        }
    }
}

class Level2Handler extends Handler {
    public void handleRequest(int level) {
        if (level <= 2) {
            System.out.println("Level2Handler 处理请求");
        } else if (next != null) {
            next.handleRequest(level);
        }
    }
}

测试

java 复制代码
public class Main {
    public static void main(String[] args) {
        Handler handler = new Level1Handler();
        handler.setNext(new Level2Handler());

        handler.handleRequest(1); // Level1 处理
        handler.handleRequest(2); // Level2 处理
    }
}

四、工厂模式(Factory Pattern)

模式介绍

将对象的创建和使用分离,避免直接使用 new 创建对象。

使用场景

  • 多种产品类共用一个创建接口
  • 框架中对象构造逻辑复用

示例代码

java 复制代码
interface Animal {
    void sound();
}

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

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

class AnimalFactory {
    public static Animal createAnimal(String type) {
        if ("dog".equalsIgnoreCase(type)) return new Dog();
        if ("cat".equalsIgnoreCase(type)) return new Cat();
        throw new IllegalArgumentException("未知动物类型");
    }
}

测试

java 复制代码
public class Main {
    public static void main(String[] args) {
        Animal dog = AnimalFactory.createAnimal("dog");
        dog.sound();

        Animal cat = AnimalFactory.createAnimal("cat");
        cat.sound();
    }
}

五、代理模式(Proxy Pattern)

模式介绍

为对象提供一种代理,以控制对其的访问。

使用场景

  • 日志、权限控制、延迟加载等
  • AOP 代理

示例代码

java 复制代码
interface Service {
    void doAction();
}

class RealService implements Service {
    public void doAction() {
        System.out.println("真实服务执行操作");
    }
}

class ProxyService implements Service {
    private RealService realService;

    public void doAction() {
        System.out.println("代理开始日志记录...");
        if (realService == null) {
            realService = new RealService();
        }
        realService.doAction();
        System.out.println("代理结束日志记录...");
    }
}

测试

java 复制代码
public class Main {
    public static void main(String[] args) {
        Service service = new ProxyService();
        service.doAction();
    }
}

总结

设计模式 应用场景 优点 常见应用
单例模式 全局唯一对象 节省资源,全局访问 Spring容器、配置类
策略模式 算法可替换 解耦、易扩展 支付方式、推荐算法
责任链模式 多级处理流程 解耦责任方,灵活添加处理器 Servlet 过滤器链
工厂模式 创建对象逻辑统一 解耦创建与使用 Spring BeanFactory
代理模式 功能增强与权限控制 降低耦合,增加附加功能 AOP 日志、安全校验

设计模式不仅仅是理论,更是写出“可读、可扩展、可维护”代码的利器。希望本文能帮助你更好地掌握这些经典模式,在项目中运用自如。

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句