观察者模式简要记录


/**
 * @author fangdayang
 * @Package com.study.design.observer
 * @date 2021/2/16 16:21
 * 基本观察者模式是有观察者和被观察者,如女孩子对你说话,男孩子进行回复,最傻的方式是一直在等待,对方的说话,
 * 但是现在的微信都会有提示功能;
 * 会发出提示铃声,呼吸灯会亮,不过这些都可以设置
 * 但是其他的信息,比如app上面推送的广告,我们就不会提示铃声
 * 下面的程序中,定义了被观察者,观察者,事件,触发的动作,将观察者和被观察者进行了分别的抽象,
 * 使之耦合度更低 与责任链最大的区别是没有回溯
 * 回溯可以理解为,请求request处理完了,可以在反过来处理返回response
 */
public class Main_Observer {
    public static void main(String[] args) {
        Computer computer = new Computer();
        computer.addActionListener(new MyActionListener()).addActionListener(new MyActionListener2());
        ActionEvent e= new ActionEvent("keyWord", new Person());
        computer.computerDoSomething(e);
    }
}
/**
 * @author fdy
 * @date 2021/2/16 16:44
 * 被观察者
 * @return {@link null}
 */

class Computer{

    List<ActionListener> listeners = new ArrayList<>();

    public Computer addActionListener(ActionListener e){
        listeners.add(e);
        return this;
    }
    public void computerDoSomething(ActionEvent e){
        for (ActionListener listener : listeners) {
            listener.handleEvent(e);
        }
    }
}
/**
 * @author fdy
 * @date 2021/2/16 16:30
 * 观察者
 * @return {@link null}
 */
interface ActionListener{
    void handleEvent(ActionEvent event);
}

class MyActionListener implements ActionListener{

    @Override
    public void handleEvent(ActionEvent event) {
        if (event.getObject() instanceof Person){
            System.out.println("进入这里面进行操作");
        }
        System.out.println("MyActionListener");
    }
}

class MyActionListener2 implements ActionListener{

    @Override
    public void handleEvent(ActionEvent event) {
        System.out.println("MyActionListener2");
    }
}


/**
 * @author fdy
 * @date 2021/2/16 16:24
 * 事件
 * @return {@link null}
 */
class ActionEvent implements Serializable {
    private String type;
    private Object object;

    public ActionEvent(String type, Object object) {
        this.type = type;
        this.object = object;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值