这个DOME的应用场景是,当股票价格波动超过5%的时候通知所有投资者,如果超出了投资者的预设股价就买入,如果低于投资者的预设股价就卖出
首先给出Observable类,就是subject,我理解为就是管理通知类
//subject管理类
/**
* Observable是一个实际的类,而JAVA是单继承模式,矛盾???(后面给出解决方案)
*/
public class Stock extends Observable {
private static final float maxGainAndLoss = 0.05f;
private float price;
public Stock(float price) {
this.price = price;
}
public void setPrice(float newPrice) {
//在条件语句中抛出一个异常后面的程序不会执行
if (newPrice<0){
throw new IllegalArgumentException("Price can not be negative");
}
float oldPrice = price;
price = newPrice;
float GainAndLoss = (newPrice - oldPrice)/oldPrice;
if (abs(GainAndLoss)> maxGainAndLoss){
//在调用notifyObservers之前,必须调用setchange方法,设置状态发生了改变,否则不会触发通知
setChanged();
//通知所有的观察者,java封装的观察者是倒序通知观察者
notifyObservers(price);
}
}
}
然后给出机构投资者和个人投资者两个观察者
/**
* 个人投资者
*/
public class PrivateInvestor implements Observer {
private String name;
private float maxPrice;
private float minPrice;
public PrivateInvestor(String name, float maxPrice, float minPrice,Stock stock) {
this.name = name;
this.maxPrice = maxPrice;
this.minPrice = minPrice;
stock.addObserver(this);
}
@Override
public void update(Observable o, Object arg) {
// System.out.println("个人先");
float price = (float) arg;
if (price>maxPrice){
System.out.println("我是个人,该卖了!");
}
if (price<minPrice){
System.out.println("我是个人,该买了!");
}
}
}
/**
* 机构投资观察者
*/
public class InstitutionalInvestor implements Observer {
private String name;
private float maxPrice;
private float minPrice;
public InstitutionalInvestor(String name, float maxPrice, float minPrice,Stock stock) {
this.name = name;
this.maxPrice = maxPrice;
this.minPrice = minPrice;
//将主题和观察者关联起来
stock.addObserver(this);
}
@Override
public void update(Observable o, Object arg) {
// System.out.println("机构先");
float price = (float) arg;
if (price>maxPrice){
System.out.println("我是机构,该卖了!");
}
if (price<minPrice){
System.out.println("我是机构,该买了!");
}
}
}
下面给出测试代码(这里使用是Android Studio的IDE)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Stock stock = new Stock(19f);
PrivateInvestor privateInvestor
= new PrivateInvestor("王老六", 20f, 18.9f, stock);
InstitutionalInvestor institutionalInvestor
= new InstitutionalInvestor("平安证券", 20f, 18.5f, stock);
stock.setPrice(18.0224f);
stock.setPrice(20.923f);
}
}
给出测试结果
有个疑问,java自带的观察者应该是倒序通知,不过我这里却是正序通知?如有大神知晓请在评论解惑,谢谢!
下面我们再说一下单继承和observable鱼和熊掌不可兼得的事情,还是用一个DOME来说,简单明了
因为setChanged是个protected的方法,所以必须重写此方法,使其public
public class NewObservable extends Observable {
@Override
public synchronized void setChanged() {
super.setChanged();
}
}
现在只需要将上面的Dome中的stock类改成如下的类,然后使用NewObservable即可
public class PersonObservale extends Person{
int age;
NewObservable newOB = new NewObservable();
}