观察者模式(Observer Pattern)主要针对对象间的一对多关系,当一个对象发生改变时,所有依赖它的对象都会得到通知,然后这些执行相应的操作。
一、需求举例:
1.当产品经理发布新的需求后,高级架构师负责技术预调研,中级工程师开发demo,初级工程师开始技术储备。
二、类图
三、代码实例
1.观察者父类:EngineerObserver
package com.lance.observer;
public abstract class EngineerObserver {
public abstract void update();
}
2.产品经理主题类:ProductManagerSubject
package com.lance.observer;
import java.util.ArrayList;
import java.util.List;
public class ProductManagerSubject {
private List<EngineerObserver> observers = new ArrayList<>();
private int requestDocumentState;
public void addObserver(EngineerObserver observer) {
observers.add(observer);
}
public void setRequestDocumentState(int requestDocumentState) {
this.requestDocumentState = requestDocumentState;
noticeObservers();
}
private void noticeObservers() {
for (EngineerObserver observer : observers) {
observer.update();
}
}
}
3.初级工程师类:JuniorEngineer
package com.lance.observer;
public class JuniorEngineer extends EngineerObserver {
@Override
public void update() {
System.out.println("Junior Engineer base technical study.");
}
}
4.中级工程师类:IntermediateEngineer
package com.lance.observer;
public class IntermediateEngineer extends EngineerObserver {
@Override
public void update() {
System.out.println("Intermediate Engineer develop demo.");
}
}
5.高级工程师类:SeniorEngineer
package com.lance.observer;
public class SeniorEngineer extends EngineerObserver {
@Override
public void update() {
System.out.println("Senior Engineer technology survey.");
}
}
6.主类:ObserverPattern
package com.lance.observer;
public class ObserverPattern {
public static void main(String[] args) {
System.out.println("==========start==========");
ProductManagerSubject subject = new ProductManagerSubject();
subject.addObserver(new IntermediateEngineer());
subject.addObserver(new JuniorEngineer());
subject.addObserver(new SeniorEngineer());
subject.setRequestDocumentState(1);
System.out.println("==========end==========");
}
}
输出结果:
==========start==========
Intermediate Engineer develop demo.
Junior Engineer base technical study.
Senior Engineer technology survey.
==========end==========
网友评论