![](https://img-blog.csdnimg.cn/b9889075eeef4c28b51dd65ab8e41307.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6IuP55av5a2Q77yM5LiT5rOo5LqO5a2m5Lmg,size_20,color_FFFFFF,t_70,g_se,x_16)
观察者observer:事件处理模型
- 事件原对象:产生对象
- 事件观察者:一堆observer
- 事件监听者:事件类型
- 归集:observer和event关联,source和event关联,但是observer和event无关联,所以在event中包含属性:
观察者模式demo
package com.fengzi.tank.observer;
import java.util.ArrayList;
import java.util.List;
/**
* @author:
* @Date:2021/12/27/11:36
* @Description
*/
public class ChildObserver {
static class Child {
boolean cry = false;
/**
* @Description: 定义观察者模式集合
* @Param:
* @return:
* @Date: 2021/12/27
*/
List<Observe> list = new ArrayList<>();
/**
* @Description: 加入观察者对象
* @Param:
* @return:
* @Date: 2021/12/27
*/ {
list.add(new Dad());
list.add(new Mum());
list.add(new Dog());
}
public boolean isCry() {
return cry;
}
public void waked() {
cry = true;
//封装观察者事件
WeakEvent event = new WeakEvent(System.currentTimeMillis(), "家里", this);
//观察者开始执行
for (Observe observe : list) {
observe.actionOnWaked(event);
}
}
}
/**
* @Description: 所有事件父类
* @Param:
* @return:
* @Date: 2021/12/27
*/
static abstract class EventObject {
//事件源
protected Object source;
/**
* @Description: 获取事件源
* @Param: []
* @return: java.lang.Object
* @Date: 2021/12/27
*/
public abstract Object getSourcr();
public EventObject(Object source){
this.source = source;
}
}
/**
* @Description: 观察者模式-封装事件监听
* @Param:
* @return:
* @Date: 2021/12/27
*/
static class WeakEvent extends EventObject {
long timestamp;
String localtion;
public WeakEvent(Long timestamp, String localtion, Object source) {
super(source);
this.timestamp = timestamp;
this.localtion = localtion;
}
/**
* The object on which the Event initially occurred.
*
* @return The object on which the Event initially occurred.
*/
@Override
public Object getSourcr() {
return source;
}
}
/**
* @Description: 观察者模式接口
* @Param:
* @return:
* @Date: 2021/12/27
*/
interface Observe {
void actionOnWaked(WeakEvent event);
}
static class Dad implements Observe {
public void feed() {
System.out.println("dad feed...");
}
@Override
public void actionOnWaked(WeakEvent event) {
feed();
System.out.println("dad event" + event.getSourcr());
}
}
static class Mum implements Observe {
public void hug() {
System.out.println("Mum hug...");
}
@Override
public void actionOnWaked(WeakEvent event) {
hug();
}
}
static class Dog implements Observe {
public void eat() {
System.out.println("dog eat...");
}
@Override
public void actionOnWaked(WeakEvent event) {
eat();
}
}
public static void main(String[] args) {
Child c = new Child();
//do sth....
c.waked();
}
}