最近设计模式越来越受到企业和程序员的重视了, 自己作为初学者,将自己学习的点滴贴到博客园,分享一下~
java.util包里面提供了对观察者模式的支持,下面是模仿着其中的Observer和Observable写出了我的观察者模式代码。
package com.myobserver; public interface Observer { void update(Observable obs, Object obj); }
package com.myobserver; public interface Observable { public void addObserver(Observer obs); public void deleteObserver(Observer obs); public void notifyObservers(Object obj); }
package com.myobserver; import java.util.ArrayList; import java.util.List; public class ConcreteObservable implements Observable { List<Observer> list = new ArrayList<Observer>(); @Override public void addObserver(Observer obs) { // TODO Auto-generated method stub list.add(obs); } @Override public void deleteObserver(Observer obs) { // TODO Auto-generated method stub list.remove(obs); } @Override public void notifyObservers(Object obj) { // TODO Auto-generated method stub for (Observer observer : list) { observer.update(this, obj); } } }
package com.myobserver; public class ConcreteObserver implements Observer { @Override public void update(Observable obs, Object obj) { // TODO Auto-generated method stub System.out.println("------------ConcreteObserver received update info" + obj + " from" + obs); } }
package com.myobserver; public class ConcreteObserver2 implements Observer { @Override public void update(Observable obs, Object obj) { // TODO Auto-generated method stub System.out.println("------------ConcreteObserver2 received update info" + obj + " from" + obs); } }
package com.myobserver; public class test { public static void main(String[] args) { ConcreteObservable observable = new ConcreteObservable(); ConcreteObserver observer1 = new ConcreteObserver(); ConcreteObserver2 observer2 = new ConcreteObserver2(); observable.addObserver(observer1); observable.addObserver(observer2); observable.notifyObservers(" Send a broacast "); } }
输出结果: ------------ConcreteObserver received update info Send a broacast [email protected] ------------ConcreteObserver2 received update info Send a broacast [email protected]
这里主要是为了了解设计模式的思想,所以没有考虑多线程同步。
时间: 2024-10-08 18:14:54