Observable是一个类当一个类需要被观察的时候应该继承这个类
Obserber是一个接口 当要产生一个观察者的动作的时候应该要覆写里面的update方法 里面一个参数是这个Observable对象o一个就是观察改变的object对象arg
通过setChanged设置变化点notifyObservers唤醒观察者二者不可或缺否则无效
通过instanceof 在update里面来判断相应的动作(如果是这个改变的对象才采取行动)
import java.util.*;
class Percent
{
private float percent;
public Percent(float Percent)
{
this.percent=Percent;
}
public void setPercent(float percent)
{
this.percent=percent;
}
public float getPercent()
{
return this.percent;
}
}
class Supermarket extends Observable
{
private float price;
private Percent percent;
private String name;
public void setPrice(float price)
{
setChanged();
notifyObservers(price);
this.price=price;
}
public void setName(String name)
{
setChanged();
notifyObservers(name);
this.name=name;
}
public void setPercent(Percent percent)
{
setChanged();
notifyObservers(percent);
this.percent=percent;
}
public Supermarket(float price,String name,Percent percent)
{
this.price=price;
this.name=name;
this.percent=percent;
}
public String toString()
{
return "名称:"+this.name+"\t\t价格:"+this.price+"\t\t百分率:"+this.percent.getPercent();
}
}
class PriceObservers implements Observer
{
private Float price;
public void update(Observable o,Object arg)
{
if(arg instanceof Float)
{
this.price=(Float)arg;
System.out.println("改变后价格是:"+price.floatValue());
}
}
}
class NameObservers implements Observer
{
private String name;
public void update(Observable o,Object arg)
{
if(arg instanceof String)
{
this.name=(String)arg;
System.out.println("改变后名称是:"+name);
}
}
}
class PercentObservers implements Observer
{
private Percent percent;
public void update(Observable o,Object arg)
{
if(arg instanceof Percent)
{
this.percent=(Percent)arg;
System.out.println("改变后百分率是:"+percent.getPercent());
}
}
}
public class override
{
public static void main(String args[])
{
Percent per = new Percent(0.374f);
Supermarket st = new Supermarket(10.5f,"肉",per);
NameObservers ns = new NameObservers();
PriceObservers ps = new PriceObservers();
PercentObservers pos = new PercentObservers();
st.addObserver(ns);
st.addObserver(ps);
st.addObserver(pos);
System.out.println(st);
st.setName("猪肉");
st.setPercent(new Percent(0.441f));
st.setPrice(13.5f);
}
}