用java写出某实时在线股票软件,该软件需提供如下功能: * 当股票购买者(Investor)所购买的某支股票(Stock)价格变化幅度达到5%时,系统将自动发送通知(包括新价格)给购买该股票的所有股民。
时间: 2024-01-07 19:06:02 浏览: 42
以下是使用Java实现的代码示例:
```java
import java.util.ArrayList;
import java.util.List;
// 抽象主题类
abstract class Stock {
private String symbol; // 股票代码
private double price; // 股票价格
private List<Investor> investors = new ArrayList<>(); // 观察者列表
public Stock(String symbol, double price) {
this.symbol = symbol;
this.price = price;
}
public String getSymbol() {
return symbol;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (Math.abs(price - this.price) / this.price >= 0.05) {
this.price = price;
notifyInvestors();
}
}
public void attach(Investor investor) {
investors.add(investor);
}
public void detach(Investor investor) {
investors.remove(investor);
}
public void notifyInvestors() {
for (Investor investor : investors) {
investor.update(this);
}
}
}
// 具体股票类
class ConcreteStock extends Stock {
public ConcreteStock(String symbol, double price) {
super(symbol, price);
}
}
// 抽象观察者类
interface Investor {
void update(Stock stock);
}
// 具体观察者类
class ConcreteInvestor implements Investor {
private String name; // 股民姓名
public ConcreteInvestor(String name) {
this.name = name;
}
@Override
public void update(Stock stock) {
System.out.println("股票代码:" + stock.getSymbol() + ",新价格:" + stock.getPrice() + ",通知股民:" + name);
}
}
// 测试类
public class StockMarket {
public static void main(String[] args) {
ConcreteStock stock = new ConcreteStock("AAPL", 150.0);
ConcreteInvestor investor1 = new ConcreteInvestor("张三");
ConcreteInvestor investor2 = new ConcreteInvestor("李四");
stock.attach(investor1);
stock.attach(investor2);
stock.setPrice(200.0); // 价格变化幅度超过5%,触发通知
}
}
```
在上面的代码中,抽象主题类 Stock 定义了添加观察者、删除观察者、通知观察者和判断价格变化幅度是否达到5%的方法。具体股票类 ConcreteStock 继承了 Stock 类,并实现了价格变化和通知观察者的方法。抽象观察者类 Investor 定义了更新股票价格和发送通知的方法,具体观察者类 ConcreteInvestor 继承了 Investor 类,并实现了具体的更新股票价格和发送通知的方法。
在测试类 StockMarket 中,创建了一个 ConcreteStock 对象和两个 ConcreteInvestor 对象,并将两个观察者对象添加到 ConcreteStock 对象的观察者列表中。然后通过调用 ConcreteStock 对象的 setPrice 方法改变股票价格,当价格变化幅度超过5%时,触发了通知,通知被添加到 ConcreteStock 对象观察者列表中的所有观察者对象。