java实现观察者模式
刚才弄了一个javascript的观察者模式,现在把java版的也传上来,以后偶尔也可以了解哈,没有定义发布者接口,直接用一个具体类表示发布者
发布者
package sample.observer;import java.util.ArrayList;import java.util.List;public class Subject {private List<IObserver> allObserver = new ArrayList<IObserver>();private int state = 0;public void attach(IObserver observer) {allObserver.add(observer);}public void detach(IObserver observer) {allObserver.remove(observer);}public void notifyObservers() {if (state != 0) {for (IObserver observer : allObserver) {observer.update();}}}public int getState() {return state;}public void setState(int state) {this.state = state;}}
?
观察者接口
package sample.observer;public interface IObserver {public void update();}
?
观察者一
package sample.observer;public class Observer1 implements IObserver {@Overridepublic void update() {System.out.println("I AM OBSERVER1 ,I UPDATE");}}
?
观察者二
package sample.observer;public class Observer2 implements IObserver {@Overridepublic void update() {System.out.println("I AM OBSERVER2 ,I UPDATE");}}
?
主函数
package sample.observer;public class Main {public static void main(String[] args) {Subject subject = new Subject();IObserver observer1 = new Observer1();IObserver observer2 = new Observer2();subject.attach(observer1);subject.attach(observer2);subject.notifyObservers();subject.setState(1);subject.notifyObservers();subject.detach(observer1);subject.notifyObservers();}}
?附件是项目代码