无
参考得网址:https://blog.csdn.net/ma598214297/article/details/80557821
----------------------------------01
抽象观察者,具体观察者:
抽象主题,具体主题:
具体观察者订阅具体的主题。
----------------------------------02
1.定义抽象的观察者和抽象的主题
package com.mayikt.observer;
/**
* @author
* @title: ObServer 抽象观察者
* @description:
* @date 2019/5/2117:20
*/
public interface ObServer {
/**
* 更新消息内容
*
* @param message
* @return
*/
public void update(String message);
}
package com.mayikt.subject;
import com.mayikt.observer.ObServer;
/**
* @author
* @title: AbstractSubject
* @description:
* @date 2019/5/2117:22
*/
public interface AbstractSubject {
/**
* 添加obServer
*
* @param obServer
*/
void addObServer(ObServer obServer);
/**
* 移除obServer
*
* @param obServer
*/
void removeObServer(ObServer obServer);
/**
* 通知所有的notifyObServerAll
*
* @param message
*/
void notifyObServerAll(String message);
/**
* 设置更新内容
*/
void setNtifyMessage(String message);
}
2.定义具体的观察者和具体的主题:
package com.mayikt.observer.impl;
import com.mayikt.observer.ObServer;
/**
* @author
* @title: UserObServer
* @description:
* @date 2019/5/2117:37
*/
public class UserObServer implements ObServer {
/**
* 订阅者用户名称
*/
private String name;
/**
* 发送内容
*/
private String message;
public UserObServer(String name) {
this.name = name;
}
public void update(String message) {
this.message = message;
read();
}
public void read() {
System.out.println(name + ",老师收到推送消息:" + message);
}
}
package com.mayikt.subject.impl;
import com.mayikt.observer.ObServer;
import com.mayikt.subject.AbstractSubject;
import java.util.ArrayList;
import java.util.List;
/**
* @author
* @title: WeChatSubject
* @description:
* @date 2019/5/2117:31
*/
public class WeChatSubject implements AbstractSubject {
/**
* 存放所有的ObServer 主题存放所有的观察者
*/
private List<ObServer> listObServer = new ArrayList<ObServer>();
/**
* 更新的内容
*/
private String message;
public void addObServer(ObServer obServer) {
listObServer.add(obServer);
}
public void removeObServer(ObServer obServer) {
listObServer.remove(obServer);
}
public void notifyObServerAll(String message) {
for (int i = 0; i < listObServer.size(); i++) {
ObServer obServer = listObServer.get(i);
obServer.update(message);
}
}
public void setNtifyMessage(String message) {
this.message = message;
System.out.println("微信公众号设置message:" + message);
notifyObServerAll(message);
}
}
一个主题有很多观察者订阅的。
测试:
public static void main(String[] args) {
// 1.注册主题
AbstractSubject weChatSubject = new WeChatSubject();
// 2.添加观察者 订阅主题
weChatSubject.addObServer(new UserObServer("你"));
weChatSubject.addObServer(new UserObServer("我"));
// 3.设置发送消息
weChatSubject.setNtifyMessage("发消息");
}
----------------------------------03
观察者的真实的应用场景:
主题是用户下单 观察者是短信通知 邮件通知 和 微信通知
JDK帮我们实现的观察者模式(Observer):
/*
* Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.util;
/**
* A class can implement the <code>Observer</code> interface when it
* wants to be informed of changes in observable objects.
*
* @author Chris Warth
* @see java.util.Observable
* @since JDK1.0
*/
public interface Observer {
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
* method.
*/
void update(Observable o, Object arg);
}
点进去Observable 是我们具体的实现的主题
/*
* Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.util;
/**
* This class represents an observable object, or "data"
* in the model-view paradigm. It can be subclassed to represent an
* object that the application wants to have observed.
* <p>
* An observable object can have one or more observers. An observer
* may be any object that implements interface <tt>Observer</tt>. After an
* observable instance changes, an application calling the
* <code>Observable</code>'s <code>notifyObservers</code> method
* causes all of its observers to be notified of the change by a call
* to their <code>update</code> method.
* <p>
* The order in which notifications will be delivered is unspecified.
* The default implementation provided in the Observable class will
* notify Observers in the order in which they registered interest, but
* subclasses may change this order, use no guaranteed order, deliver
* notifications on separate threads, or may guarantee that their
* subclass follows this order, as they choose.
* <p>
* Note that this notification mechanism has nothing to do with threads
* and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
* mechanism of class <tt>Object</tt>.
* <p>
* When an observable object is newly created, its set of observers is
* empty. Two observers are considered the same if and only if the
* <tt>equals</tt> method returns true for them.
*
* @author Chris Warth
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
* @see java.util.Observer
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
* @since JDK1.0
*/
public class Observable {
private boolean changed = false;//是否群发
private Vector<Observer> obs;//观察者集合
/** Construct an Observable with zero Observers. */
public Observable() {
obs = new Vector<>();
}
/**
* Adds an observer to the set of observers for this object, provided
* that it is not the same as some observer already in the set.
* The order in which notifications will be delivered to multiple
* observers is not specified. See the class comment.
*
* @param o an observer to be added.
* @throws NullPointerException if the parameter o is null.
*/
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
/**
* Deletes an observer from the set of observers of this object.
* Passing <CODE>null</CODE> to this method will have no effect.
* @param o the observer to be deleted.
*/
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
/**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to
* indicate that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and <code>null</code>. In other
* words, this method is equivalent to:
* <blockquote><tt>
* notifyObservers(null)</tt></blockquote>
*
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers() {
notifyObservers(null);
}
/**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to indicate
* that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and the <code>arg</code> argument.
*
* @param arg any object.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
/**
* Clears the observer list so that this object no longer has any observers.
*/
public synchronized void deleteObservers() {
obs.removeAllElements();
}
/**
* Marks this <tt>Observable</tt> object as having been changed; the
* <tt>hasChanged</tt> method will now return <tt>true</tt>.
*/
protected synchronized void setChanged() {
changed = true;
}
/**
* Indicates that this object has no longer changed, or that it has
* already notified all of its observers of its most recent change,
* so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
* This method is called automatically by the
* <code>notifyObservers</code> methods.
*
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
protected synchronized void clearChanged() {
changed = false;
}
/**
* Tests if this object has changed.
*
* @return <code>true</code> if and only if the <code>setChanged</code>
* method has been called more recently than the
* <code>clearChanged</code> method on this object;
* <code>false</code> otherwise.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#setChanged()
*/
public synchronized boolean hasChanged() {
return changed;
}
/**
* Returns the number of observers of this <tt>Observable</tt> object.
*
* @return the number of observers of this object.
*/
public synchronized int countObservers() {
return obs.size();
}
}
----------------------------------04
利用JDK的观察者模式,实现用户下单发送消息邮件通知等。
定义主题:
package com.mayikt.jdk.subject;
import java.util.Observable;
/**
* @author
* @title: Message
* @description:
* @date 2019/5/2117:51
*/
public class MessageObServable extends Observable {
@Override
public void notifyObservers(Object arg) {
// 1.改变数据
setChanged();
// 2.通知所有的观察者改变
super.notifyObservers(arg);
}
}
定义两个观察者:
package com.mayikt.jdk.observer;
import com.mayikt.jdk.subject.MessageObServable;
import java.util.Observable;
import java.util.Observer;
/**
* @author
* @title: EmailObServer
* @description:
* @date 2019/5/2117:55
*/
public class EmailObServer implements Observer {
public void update(Observable o, Object arg) {
// 1.获取主题
MessageObServable messageObServable = (MessageObServable) o;
System.out.println("发送邮件内容:" + arg);
}
}
package com.mayikt.jdk.observer;
import java.util.Observable;
import java.util.Observer;
/**
* @author
* @title: SmsObServer
* @description:
* @date 2019/5/2117:54
*/
public class SmsObServer implements Observer {
public void update(Observable o, Object arg) {
System.out.println("发送短信内容:" + arg);
}
}
测试:
package com.mayikt.jdk.subject;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.jdk.observer.EmailObServer;
import com.mayikt.jdk.observer.SmsObServer;
import java.util.Observer;
/**
* @author
* @title: JdkObServer
* @description:
* @date 2019/5/2117:52
*/
public class JdkObServer {
public static void main(String[] args) {
//1.创建主题
MessageObServable messageObServable = new MessageObServable();
// 2.添加订阅者
messageObServable.addObserver(new EmailObServer());
messageObServable.addObserver(new SmsObServer());
// 3.组装消息内容
JSONObject jsonObject = new JSONObject();
jsonObject.put("email", "644064779@qq.com");
jsonObject.put("phone", "15123456789");
jsonObject.put("text", "恭喜您以1399.00元购买蚂蚁课堂永久会员.");
messageObServable.notifyObservers(jsonObject.toJSONString());
}
}
使用JDK的观察者模式
将观察者注册到主题中群发消息。
----------------------------------05
在spring如何实现观察者模式:
package com.mayikt.service;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Application;
import lombok.Data;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
import javax.annotation.sql.DataSourceDefinition;
/**
* @author
* @title: OrderCreateEvent 订单消息活动时间
* @description:
* @date 2019/5/2119:14
*/
public class OrderCreateEvent extends ApplicationEvent {
private JSONObject jsonObject;
public OrderCreateEvent(Object source, JSONObject jsonObject) {
super(source);
this.jsonObject = jsonObject;
}
public JSONObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
}
这个就是消息的内容也就是事件。
创建两个监听,直接抛给容器去自动组装。
package com.mayikt.service.listener;
import com.mayikt.service.OrderCreateEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author
* @title: SmsListener
* @description:
* @date 2019/5/2119:19
*/
@Component
public class EmailListener implements ApplicationListener<OrderCreateEvent> {
@Override
@Async
public void onApplicationEvent(OrderCreateEvent event) {
System.out.println(Thread.currentThread().getName()+"发送邮件内容:" + event.getJsonObject().toJSONString());
}
}
package com.mayikt.service.listener;
import com.mayikt.service.OrderCreateEvent;
import javafx.application.Application;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author
* @title: SmsListener
* @description:
* @date 2019/5/2119:19
*/
@Component
public class SmsListener implements ApplicationListener<OrderCreateEvent> {
@Override
@Async
public void onApplicationEvent(OrderCreateEvent event) {
System.out.println(Thread.currentThread().getName() + "发送短信内容:" + event.getJsonObject().toJSONString());
}
}
就是观察者
写controller
package com.mayikt.controller;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.service.OrderCreateEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author
* @title: OrderController
* @description:
* @date 2019/5/2119:22
*/
@RestController
public class OrderController {
@Resource
private ApplicationContext applicationContext;
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
@RequestMapping("/addOrder")
public String addOrder() {
System.out.println("创建订单...");
// 3.组装消息内容
JSONObject jsonObject = new JSONObject();
jsonObject.put("email", "644064779@qq.com");
jsonObject.put("phone", "15123456789");
jsonObject.put("text", "恭喜您以1399.00元购买蚂蚁课堂永久会员.");
OrderCreateEvent orderCreateEvent = new OrderCreateEvent(this, jsonObject);
applicationContext.publishEvent(orderCreateEvent);
return "success";
}
}
----------------------------------06