Java内置的“观察者”
目前还不知道为什么JAVA里会内置观察者模式的实现,不过据说观察者是JDK中最常见的设计模式了……
还是技术支持中心选“三八红旗手”的事儿,subject(主题)的代码:
package subject;
import java.util.Observable;
public class Center38 extends Observable {
private int a;
private int b;
private int c;
public void measurementsChanged() {
setChanged();
notifyObservers();
}
public void setABC(int a1, int b1, int c1) {
this.a = a1;
this.b = b1;
this.c = c1;
measurementsChanged();
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public int getC() {
return c;
}
}
import java.util.Observable;
public class Center38 extends Observable {
private int a;
private int b;
private int c;
public void measurementsChanged() {
setChanged();
notifyObservers();
}
public void setABC(int a1, int b1, int c1) {
this.a = a1;
this.b = b1;
this.c = c1;
measurementsChanged();
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public int getC() {
return c;
}
}
可以发现,嘿嘿,不用自己写接口了(自由度下降了),下面是 observer(观察者)要实现的接口:
package observer;
public interface Iuser {
public void display();
}
public interface Iuser {
public void display();
}
简单吧,简单的不成样子了,然后是观察者的代码:
package observer;
import java.util.Observable;
import java.util.Observer;
import subject.Center38;
public class User1 implements Observer, Iuser {
private int a1;
private int b1;
private int c1;
Observable c38;
public User1(Observable input38){
this.c38=input38;
c38.addObserver(this);
}
public void display() {
System.out.println("我是刘德华,我收到的最新投票结果是:");
System.out.println("a:"+a1);
System.out.println("b:"+b1);
System.out.println("c:"+c1);
}
public void update(Observable ob, Object arg1) {
if(ob instanceof Center38)
{
Center38 c38 = (Center38)ob;
this.a1=c38.getA();
this.b1=c38.getB();
this.c1=c38.getC();
display();
}
}
}
import java.util.Observable;
import java.util.Observer;
import subject.Center38;
public class User1 implements Observer, Iuser {
private int a1;
private int b1;
private int c1;
Observable c38;
public User1(Observable input38){
this.c38=input38;
c38.addObserver(this);
}
public void display() {
System.out.println("我是刘德华,我收到的最新投票结果是:");
System.out.println("a:"+a1);
System.out.println("b:"+b1);
System.out.println("c:"+c1);
}
public void update(Observable ob, Object arg1) {
if(ob instanceof Center38)
{
Center38 c38 = (Center38)ob;
this.a1=c38.getA();
this.b1=c38.getB();
this.c1=c38.getC();
display();
}
}
}
同理我还写了user2和user3,大概和user1没区别,于是不粘帖了,最后是测试的代码:
package test;
import observer.User1;
import observer.User3;
import observer.User2;
import subject.Center38;
public class Test {
public static void main(String[] args) {
Center38 c38= new Center38();
User1 u1= new User1(c38);
User2 u2= new User2(c38);
User3 u3= new User3(c38);
c38.setABC(132,1234,122);
}
}
import observer.User1;
import observer.User3;
import observer.User2;
import subject.Center38;
public class Test {
public static void main(String[] args) {
Center38 c38= new Center38();
User1 u1= new User1(c38);
User2 u2= new User2(c38);
User3 u3= new User3(c38);
c38.setABC(132,1234,122);
}
}
运行结果: