11.22實驗 21:觀察者模式

發表於2024-12-02

[實驗任務一]:股票提醒

當股票的價格上漲或下降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. 注意程式設計規範。

相關文章