个人理解,观察者模式就是在一个事件触发之后观察者们做系列操作
1.定义一个接口,多个观察者都实现该接口重写其方法
2.在被观察的对象里定义一个观察者容器,当事件触发,一次执行每个观察者的操作方法
3.测试类里面测试,实例化孩子类(Child1),调用孩子醒了的方法(wakeUp()),运行结果
dad feeding ...
mum huging ...
dog wang ...
package com.mashibing.dp.observer.v8;
import java.util.ArrayList;
import java.util.List;
/**
* 有很多时候,观察者需要根据事件的具体情况来进行处理
* 大多数时候,我们处理事件的时候,需要事件源对象
* 事件也可以形成继承体系
*/
class Child1{
private boolean cry = false;
List<Observer1> observer1s= new ArrayList<>();
//把观察的对象偶读放进容器
{
observer1s.add(new Dad1());
observer1s.add(new Mum1());
observer1s.add(new Dog1());
}
public boolean isCry(){
return cry;
}
wakeUpEvent1 event1 = new wakeUpEvent1(System.currentTimeMillis(), "bed",this);
public void wakeUp(){
cry=true;
//遍历观察者,执行各个观察者的方法
for (Observer1 observer1 : observer1s) {
observer1.actionOnWakeUp(event1);
}
}
}
abstract class Event1<T>{
abstract T getSource();
}
//事件类,fire Event
class wakeUpEvent1 extends Event1<Child1>{
long timestamp;
String loc;
Child1 source;
public wakeUpEvent1(long timestamp, String loc, Child1 source) {
this.timestamp = timestamp;
this.loc = loc;
this.source = source;
}
@Override
Child1 getSource() {
return source;
}
}
interface Observer1{
void actionOnWakeUp(wakeUpEvent1 event1);
}
class Dad1 implements Observer1 {
public void feed(){
System.out.println("dad feeding ...");
}
@Override
public void actionOnWakeUp(wakeUpEvent1 event1) {
feed();
}
}
class Mum1 implements Observer1 {
public void hug(){
System.out.println("mum huging ...");
}
@Override
public void actionOnWakeUp(wakeUpEvent1 event1) {
hug();
}
}
class Dog1 implements Observer1 {
public void wang(){
System.out.println("dog wang ...");
}
@Override
public void actionOnWakeUp(wakeUpEvent1 event1) {
wang();
}
}
public class Main1 {
public static void main(String[] args) {
Child1 child1 = new Child1();
// child1.isCry();
child1.wakeUp();
}
}