本文主要是介绍Design Pattern—— Observer Pattern 观察者模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Observer Pattern 观察者模式:
一.定义:
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有的观察者对象,让他们能够自动更新自己:
二.组成:
1.抽象主题角色:(也就是被观察者的抽象)
package com.designPattern.observer;public interface watched {public void addWatcher(Watcher watcher);public void removeWatcher(Watcher watcher);public void notifyAllWatcher();}
2.抽象观察者角色: (也就是观察者的抽象)
package com.designPattern.observer;public interface Watcher {public void update();
}
3.具体主题角色:(也就是具体被观察者对象)
package com.designPattern.observer;import java.util.ArrayList;
import java.util.List;public class ConcreteWatched implements watched {private List<Watcher> list = new ArrayList<Watcher>();@Overridepublic void addWatcher(Watcher watcher) {list.add(watcher);}@Overridepublic void removeWatcher(Watcher watcher) {list.remove(watcher);}@Overridepublic void notifyAllWatcher() {for (Watcher watch : list) {watch.update();}}
}
4.具体观察者角色:
package com.designPattern.observer;public class ConcreteWatcher implements Watcher {private String id;public ConcreteWatcher(String id) {this.id = id;}@Overridepublic void update() {System.out.println("i am happy! " + this.id);}
}
ok 以上是这个观察者模式的4个主要组成。 下面main调用:
package com.designPattern.observer;public class Client {public static void main(String[] args) {// 创建一个被观察者ConcreteWatched watched = new ConcreteWatched();// 创建4个观察者ConcreteWatcher watcher1 = new ConcreteWatcher("zhaan");ConcreteWatcher watcher2 = new ConcreteWatcher("lisi");ConcreteWatcher watcher3 = new ConcreteWatcher("xiaopin");// 把watcher1 到watcher3 这四个观察者注册到一个共同的主题watched上watched.addWatcher(watcher1);watched.addWatcher(watcher2);watched.addWatcher(watcher3);// 类似于addActionListener()函数把实现 ActionListener接口的类的对象注册到了button上。watched.addWatcher(new Watcher() {@Override
//类似于actionPerformed()函数
public void update() {System.out.println("i am happy!ooooooppppp ");}});watched.addWatcher(new ConcreteWatcher("hehe"));watched.notifyAllWatcher(); // 调用被观察者的notifyAllWatcher()函数,实际为遍历了所有依赖于该观察者的角色}}
输出结果:
i am happy! zhaan
i am happy! lisi
i am happy! xiaopin
i am happy!ooooooppppp
i am happy! hehe
这篇关于Design Pattern—— Observer Pattern 观察者模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!