/**
* @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;
}
}
观察者模式简要记录
最新推荐文章于 2023-09-18 11:23:43 发布