【设计模式_观察者模式/发布订阅】观察者模式_股票案列

编程中常见的技术难题有哪些?

编程中常见的技术难题有如同一道道难题,比如bug像隐藏的恶魔,让程序员们捉摸不透;性能优化就像是调整汽车引擎,需要精准的调校;还有就是跨平台兼容性,就像是翻译不同语言,需要找到最佳的沟通方式。面对这些难题,程序员们就像是解密高手,不断寻找突破口,解决问题。

题目

**任务一:使用观察者模式设计在线股票软件的股票变化功能
某在线股票软件需要提供如下功能:当股票购买者的某支股票价格变化幅度达到5%时,系统将自动发送通知(包括新价格)给购买该股票的股民。现使用观察者设计该系统。
请完成该系统类图设计和实现编程。编程实现运行结果参考下图:
**在这里插入图片描述

分析

发布/订阅模式;

  1. 通知者/发布者 (publisher)Stock
  2. 订阅者(subscriber)Investor

具体的实现,我们需要使用发布者和订阅者的接口实现类来实现;
具体:
【设计模式_观察者模式/发布订阅】观察者模式_股票案列_第1张图片
【设计模式_观察者模式/发布订阅】观察者模式_股票案列_第2张图片

Investor代表多个订阅者,可以是一个array list集合形似…

代码

publisherStock 抽象发布者

public abstract class Stock {
 protected String symbol;
 protected double price;
 private ArrayList<Investor> investors
 				=new ArrayList<Investor>();
 public Stock(String symbol, double price) {
		super(); 
		this.symbol = symbol; 
		this.price = price; 
	} 	
public String getSymbol() { 		
return symbol; 
	} 	
public void setSymbol(String symbol) { 
		this.symbol = symbol; 
	} 	
public double getPrice() {
		return price; 
	} 	
public void setPrice(double price) { 	
	this.price= price; 		
> Notify();
> } 	 	
public void Attach(Investor investor) { 		
investors.add(investor); 	
} 	 	
public void Detach(Investor investor)
{ 		
investors.remove(investor); 
	} 	
public void Notify() {
		for(Investor i:investors) 	
		i.Update(this); 
	} 
}



StockPubuliser具体发布者

public class IBM extends Stock {

	/**
	 * @param symbol
	 * @param price
	 */
	public IBM(String symbol, double price) {
		super(symbol, price);
		
	}
}

订阅者-抽象

订阅者-具体的订阅的股民

reference

reference-subscriber-publiser

你可能感兴趣的:({00}设计模式,设计模式,观察者模式,c语言,java,开发语言,1024程序员节)