【内含例子代码】Spring框架的设计模式应用(第二集)

接上一篇文章,现在继续讲一下Spring框架的设计模式应用

4. 观察者模式 (Observer Pattern)

描述:

  • 观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。当主题对象发生变化时,它的所有依赖者(观察者)都会收到通知并自动更新。

Spring 中的应用:

  • 事件机制: Spring 提供了事件发布和监听机制,允许对象之间进行松耦合的通信。

  • ApplicationEventPublisher: 用于发布事件。

  • ApplicationListener: 用于监听事件。

示例:

go 复制代码
// 定义一个事件
publicclass CustomEvent extends ApplicationEvent {
    private String message;

    public CustomEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

// 发布事件
@Service
publicclass EventPublisherService implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    public void publishCustomEvent(final String message) {
        System.out.println("Publishing custom event. ");
        CustomEvent customEvent = new CustomEvent(this, message);
        publisher.publishEvent(customEvent);
    }
}

// 监听事件
@Component
publicclass CustomEventListener implements ApplicationListener<CustomEvent> {

    @Override
    public void onApplicationEvent(CustomEvent event) {
        System.out.println("Received custom event - " + event.getMessage());
    }
}

5. 策略模式 (Strategy Pattern)

描述:

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

Spring 中的应用:

  • Routing DataSource: 在多数据源环境下,可以根据不同的条件选择不同的数据库连接。

  • Transaction Management: 可以配置不同的事务管理器。

示例:

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

publicclass CreditCardPaymentStrategy implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid with credit card: $" + amount);
    }
}

publicclass PayPalPaymentStrategy implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("Paid with PayPal: $" + amount);
    }
}

publicclass ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void checkout(int amount) {
        paymentStrategy.pay(amount);
    }
}

6. 模板方法模式 (Template Method Pattern)

描述:

  • 模板方法模式定义了一个算法的骨架,而将一些步骤延迟到子类中实现。

Spring 中的应用:

  • JdbcTemplate: 提供了一个执行 SQL 查询的基本模板,具体的查询逻辑由子类或回调函数实现。

  • HibernateTemplate: 类似地,提供了与 Hibernate 交互的基本模板。

示例:

go 复制代码
public abstractclass Game {
    protected abstract void initialize();
    protected abstract void startPlay();
    protected abstract void endPlay();

    // Template method
    public final void play() {
        // Initialize the game
        initialize();

        // Start the game
        startPlay();

        // End the game
        endPlay();
    }
}

publicclass Cricket extends Game {
    @Override
    protected void endPlay() {
        System.out.println("Cricket Game Finished!");
    }

    @Override
    protected void initialize() {
        System.out.println("Cricket Game Initialized! Enjoy the game.");
    }

    @Override
    protected void startPlay() {
        System.out.println("Cricket Game Started. Enjoy the game!");
    }
}

下集预告

下一篇文章将写上Spring框架继续介绍下面三种设计模式的应用:

7. 建造者模式 (Builder Pattern)

8. 装饰器模式 (Decorator Pattern)

9. 适配器模式 (Adapter Pattern)

go 复制代码
/// ***你们的关注是我一直写作的动力
System.out.println("请添加我的绿色公主号:");
System.out.println("Java知识日历");
相关推荐
1024奇点5 小时前
【仓颉语言入门 · 第二篇 第 22 课】
开发语言·ide·开源
实名上网宋凯宣5 小时前
Django
后端·python·django
Warren2Lynch6 小时前
C4 模型详解:利用 Visual Paradigm 可视化软件架构的综合指南
开发语言·uml
天河归来6 小时前
第三方接口不稳定,如何让核心任务继续完成
java·大数据
Knight_AL7 小时前
Java 文件下载时文件名中的 `#` 被转换成 `%23`?一次 URL 编码与解码问题排查
java·开发语言
利威尔xu7 小时前
Go IM 源码实战(14):本地缓存快 3000 倍,失效却难 10 倍
后端·缓存·微服务·面试·golang
FRing037 小时前
vue2干货总结2(v-bind、v-for、v-model、指令修饰符、v-bind操作class和style)
开发语言·前端·vue.js·vue2
逃逸线LOF8 小时前
Ribbon负载均衡原理(Irule组件、源码分析)
后端·spring cloud·ribbon
by209998 小时前
C++ 智能指针的所有权与使用
开发语言·c++·经验分享
砚底藏山河8 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融