[实验任务一]:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
实验要求:
1. 画出对应类图;
2. 提交源代码;
package observer;
import java.util.ArrayList;
public abstract class Subject {
protected ArrayList<MyObserver> observers = new ArrayList<>();
//注册
public void attach(MyObserver obs){
observers.add(obs);
}
//注销
public void detach(MyObserver obs){
observers.remove(obs);
}
//抽象改变
public abstract void up(double a);
public abstract void down(double a);
}
package observer;
public interface MyObserver {
void responseUp();
void responseDown();
}
package observer;
//股票,具体目标类
public class Stock extends Subject{
@Override
public void up(double a) {
System.out.println("股票上涨"+(a*100)+"%");
if(a>0.05){
for (MyObserver observer : observers) {
observer.responseUp();
}
}
}
@Override
public void down(double a) {
System.out.println("股票下跌"+(a*100)+"%");
if(a>0){
for (MyObserver observer : observers) {
observer.responseDown();
}
}
}
}
package observer;
public class StockHolder implements MyObserver{
@Override
public void responseUp() {
System.out.println("股票上涨,买了一些股票");
}
@Override
public void responseDown() {
System.out.println("股票下跌,哭了");
}
}
package observer;
public class Client {
public static void main(String[] args) {
Subject s = new Stock();
StockHolder h1 = new StockHolder();
s.attach(h1);
s.up(0.06);
System.out.println("-------------------");
s.down(0.06);
}
}
3. 注意编程规范。