设计模式_Observable与Observer
一.基本概念
java.util.Observable 被观察者类,需要继承这个类
java.util.Observer 观察者类,需要实现这个接口中的update()方法
二.举例 Door2
属性 name 和status 改变,被监管
1.Door2
import java.util.Observable; //被监管对象 public class Door2 extends Observable { private String state = ""; private String name = ""; public void setState(String newValue) { if (state != newValue) { this.state = newValue; // 标记此 Observable对象为已改变的对象 setChanged(); // 通知所有观察者 notifyObservers("state"); } } public void setName(String newValue) { if (name != newValue) { this.name = newValue; // 标记此 Observable对象为已改变的对象 setChanged(); // 通知所有观察者 notifyObservers("name"); } } ////////////////////////////////////////// public String getName() { return name; } public String getState() { return state; } }
2.被监管对象
Door2StateObserver
import java.util.Observable; import java.util.Observer; public class Door2StateObserver implements Observer { @Override public void update(Observable o, Object arg) { Door2 door2 = (Door2) o; if (!arg.toString().equalsIgnoreCase("state")) { return; } switch (door2.getState()) { // 使用Java 7的switch语句对string的判断支持 case "open": System.out.println("门打开"); break; case "close": System.out.println("门关闭"); break; } } }
Door2NameObserver
import java.util.Observable; import java.util.Observer; public class Door2NameObserver implements Observer { @Override public void update(Observable o, Object arg) { Door2 door2 = (Door2) o; if (!arg.toString().equalsIgnoreCase("name")) { return; } System.out.println("I got a new name,named \"" + door2.getName() + "\""); } }
3.Door2Test
public class Door2Test { public static void main(String[] args) { Door2 door = new Door2(); Observer stateListener = new Door2StateObserver(); door.addObserver(stateListener); // 开门 door.setState("open"); System.out.println("我已经进来了"); // 关门 door.setState("close"); // Observer nameListener = new Door2NameObserver(); door.addObserver(nameListener); door.setName("dengzy"); } }