Java中可以使用观察者模式开发,有三种简单的方式可以实现。
- 自定义接口实现
观察者
public interface Observer {
public void update(Object o);
}
观察者的实现
public class ObserverImpl implements Observer{
private Object str;
@Override
public void update(Object o) {
this.str = o;
System.out.println(this.str);
}
}
观察者的注入和方法调用
@Autowired
private List<Observer> observers;
@GetMapping("impl/{str}")
public void impl(@PathVariable("str") String str){
for (Observer observer : observers){
observer.update(str);
}
}
- 基于spring的事件
先定义spring事件
public class CustEvent extends ApplicationEvent {
public String msg;
public CustEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
}
事件监听器
@Component
public class CustEventListener {
@EventListener()
public void eventListen(ApplicationEvent applicationEvent){
if(applicationEvent instanceof CustEvent){
CustEvent custEvent = (CustEvent)applicationEvent;
System.out.println(custEvent.msg);
}
}
}
发布事件
@GetMapping("event/{str}")
public void event(@PathVariable("str") String str){
context.publishEvent(new CustEvent(this,str));
}
- 基于Java原生接口
实现java.util.Observer
public class JavaObserverA implements Observer {
private int myState;
@Override
public void update(Observable o, Object arg) {
myState = ((JavaConcreteSubject)o).getState();
System.out.println(myState);
}
}
继承Observable类,注意发布时要调用父类的setChanged()和notifyObservers()方法
public class JavaConcreteSubject extends Observable {
private int state;
public void set(int s){
state = s; //目标对象的状态发生了改变
setChanged(); //表示目标对象已经做了更改
notifyObservers(state); //通知所有的观察者
}
public int getState() {
return state;
}
}
注册观察者,然后发布事件
private JavaConcreteSubject subject = new JavaConcreteSubject();
public testController(){
subject.addObserver(new JavaObserverA());
}
@GetMapping("util/{str}")
public void util(@PathVariable("str") String str){
subject.set(1);
}