用观察者模式模拟小孩哭这个事件不同观察者做出的处理:
public class Child {
//默认小孩不哭
private boolean cry = false;
List<Observer> observers = new ArrayList<>();
{
observers.add(new Dad());
observers.add(new Mum());
observers.add(new Dog());
}
public boolean isCry() {
return cry;
}
public void wakeUp(){
cry = true;
//小孩醒了,创建一个事件
WakeUpEvent event = new WakeUpEvent(System.currentTimeMillis(), "bed", this);
for (Observer observer : observers) {
//各个观察者处理这个事件
observer.actionOnWakeUp(event);
}
}
}
abstract class Event<T>{
//事件源对象
abstract T getSource();
}
class WakeUpEvent extends Event<Child>{
//何时
long timestamp;
//何地
String loc;
Child source;
public WakeUpEvent(long timestamp, String loc, Child source) {
this.timestamp = timestamp;
this.loc = loc;
this.source = source;
}
@Override
Child getSource() {
return source;
}
}
interface Observer {
//处理小孩醒的事件
void actionOnWakeUp(WakeUpEvent event);
}
class Dad implements Observer{
public void feed() {
System.out.println("dad feeding...");
}
@Override
public void actionOnWakeUp(WakeUpEvent event) {
feed();
}
}
class Mum implements Observer {
public void hug() {
System.out.println("mum hugging...");
}
@Override
public void actionOnWakeUp(WakeUpEvent event) {
hug();
}
}
class Dog implements Observer {
public void wang() {
System.out.println("dog wang...");
}
@Override
public void actionOnWakeUp(WakeUpEvent event) {
wang();
}
}
class Main{
public static void main(String[] args) {
Child child = new Child();
child.wakeUp();
}
}