Observer和Observable

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);
	
		
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值