设计模式笔记之三 观察者模式
?
?
import java.util.hashmap;import java.util.map;/** * 主题类,被观察者对象 * */public class subject {private map<observer, observer> mapobserver = new hashmap<observer, observer>();/** * 注册方法,表示订阅 * @param observer */public void register(observer observer) {mapobserver.put(observer, observer);}/** * 取消订阅 * @param observer */public void unregister(observer observer) {mapobserver.remove(observer);}/** * 通知所有观察者 */public void notifyallobserver() {for (map.entry<observer, observer> entry : mapobserver.entryset()) {entry.getvalue().update();}}}/** * 观察者接口 */public interface observer {public void update();}/** * 观察者1 */public class concreteobserver1 implements observer {@overridepublic void update() {system.out.println("concreteobserver1 update...");}}/** * 观察者2 */public class concreteobserver2 implements observer {@overridepublic void update() {system.out.println("concreteobserver2 update...");}}/** * 观察者模式的使用 */public class testobserver {/** * @param args */public static void main(string[] args) {subject subject = new subject();observer observer1 = new concreteobserver1();observer observer2 = new concreteobserver2();subject.register(observer1);subject.register(observer2);subject.notifyallobserver();}}