设计模式---基于springboot-web实现得观察者模式(java)

观察者模式是一种行为设计模式, 允许你定义一种订阅机制, 可在对象事件发生时通知多个 “观察” 该对象的其他对象。

业务场景:用户下单,会触发两个业务 1减库存  2存入日志 。这两个事件互不干扰,但是需要同时进行,这时候就可以使用观察者模式分发到各自得listener里面去 

代码demo

1.创建一个观察事件

package com.cmict.core.entity;

import org.springframework.context.ApplicationEvent;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Katyusha
 * @create 2022/9/3 1:02
 */

public class User extends ApplicationEvent {

    private String userName;



    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private String password;
    public User(Object source) {
        super(source);
    }
}

2.创建listener

package com.cmict.core.listener;

import com.cmict.core.entity.User;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Katyusha
 * @create 2022/9/3 1:08
 */
@Component
public class UserTestOne implements ApplicationListener<User> {
    @Override
    public void onApplicationEvent(User user) {
        System.out.println("user"+user.toString());
    }
}
package com.cmict.core.listener;

import com.cmict.core.entity.User;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Katyusha
 * @create 2022/9/3 1:08
 */
@Component
public class UserTesTwo implements ApplicationListener<User> {
    @Override
    public void onApplicationEvent(User user) {
        System.out.println("user2"+user.toString());
    }
}

使用观察者模式

package com.cmict.core.controller;

import com.cmict.core.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Katyusha
 * @create 2022/9/3 1:17
 */
@RestController
public class UserController {
    @Autowired
    ApplicationEventPublisher applicationEventPublisher;

    @GetMapping("user")
    public String user() {
        User user = new User("1");
        user.setUserName("s");
        user.setPassword("b");
        applicationEventPublisher.publishEvent(user);
        return "success";
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值