定義:定義了對象之間一對多的依賴暇务,這樣一來泼掠,當一個對象改變時,它所有的依賴者都會收到通知并自動更新
優(yōu)點:
觀察者模式解除了主題和具體觀察者的耦合垦细,讓耦合的雙方都依賴于抽象择镇,而不是依賴具體。
從而使得各自的變化都不會影響另一邊的變化括改。
缺點:
依賴關系并未完全解除腻豌,抽象通知者依舊依賴抽象的觀察者。
適用場景:
當一個對象的改變需要給變其它對象時嘱能,而且它不知道具體有多少個對象有待改變時吝梅。
一個抽象某型有兩個方面,當其中一個方面依賴于另一個方面惹骂,這時用觀察者模式可以將
這兩者封裝在獨立的對象中使它們各自獨立地改變和復用苏携。、
/**
* @author: sjx
* @date: 2018/7/28 13:22
* @description: 圖書訂閱者
*/
public class BookSubject implements Subject {
List<Observer> observerList = new ArrayList<>();
String bookName;
@Override
public void registerObserver(Observer observer) {
if (!observerList.contains(observer)) {
observerList.add(observer);
}
}
@Override
public void removeObserver(Observer observer) {
if (observerList.contains(observer)) {
observerList.remove(observer);
}
}
@Override
public void notifyObserver() {
for (Observer observer : observerList) {
observer.update(bookName);
}
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
}
/**
* @Auther: sjx
* @Date: 2018/7/28 13:14
* @Description:
*/
public interface Observer {
void update(String name);
void disConnect();
}
/**
* @author: sjx
* @date: 2018/7/28 13:30
* @description: 被觀察者
*/
public class ReaderBook implements Observer {
private Subject subject;
public ReaderBook(Subject subject) {
this.subject = subject;
}
public void register(){
subject.registerObserver(this);
}
@Override
public void update(String name) {
System.out.println("新書來了对粪,名稱是" + name);
}
@Override
public void disConnect() {
subject.removeObserver(this);
}
}
public class Main {
public static void main(String[] args) {
Subject subject = new BookSubject();
Observer observer = new ReaderBook(subject);
((ReaderBook) observer).register();
((BookSubject) subject).setBookName("java");
subject.notifyObserver();
}
}
//java jdk對觀察者模式的支持
/**
* @author: sjx
* @date: 2018/7/28 13:46
* @description: 觀察者
*/
public class Teacher extends Observable {
String info = "";
public void setHomeWork(String work) {
info = work;
System.out.println("老師布置的作業(yè)是" + info);
//設置通知時間生效
setChanged();
notifyObservers();
}
public String getInfo() {
return info;
}
}
/**
* @author: sjx
* @date: 2018/7/28 13:47
* @description: 被觀察者
*/
public class Student implements Observer {
private String name;
public Student(String name, Observable observable) {
this.name = name;
observable.addObserver(this);
}
@Override
public void update(Observable o, Object arg) {
Teacher teacher = (Teacher) o;
System.out.println(name + "收到作業(yè)-" + teacher.getInfo());
}
}
/**
* @author: sjx
* @date: 2018/7/28 13:44
* @description: java jdk 內(nèi)置觀察者
*/
public class JdkMain {
public static void main(String[] asrgs) {
Teacher observable = new Teacher();
Student student1 = new Student("張三",observable);
Student student2 = new Student("李四",observable);
Student student3 = new Student("王五",observable);
observable.setHomeWork("第二頁第六題");
observable.setHomeWork("第三頁第七題");
observable.setHomeWork("第五頁第八題");
}
}