packagecom.v5ent.rapid4j.pattern;importjava.util.ArrayList;importjava.util.List;importjava.util.Observable;importjava.util.Observer;importjava.util.Random;/*** American Stock Exchange market(ASE) has a list of stocks.A stock object has two perspective information,symbol and price.
* Class StockMarket is a class that represents the stock market.
* Its constructor generates a collection of stocks using random numbers to build 3-letter stock symbols and random numbers for initial stock price.
* Implement a Java application when the stock price has been changed,all those investors who are interested in the stock market will be notified by receiving the most recent price.
* Create a driver class to test your implementation.
*@authorMignet
**/
public classStockTest {public static voidmain(String[] args) {
StockMarket market= new StockMarket(10);
market.show();
market.invest();
market.shuffle();
market.show();
}
}classStockMarket{private Listlist;private intcapacity;public StockMarket(intcapacity){this.capacity=capacity;
init(this.capacity);
}private List init(intn){
list= new ArrayList();for(int i=0;i
list.add(emitStock());
}returnlist;
}/*** 股票看板*/
public voidshow(){
System.out.println("-------------Welcome to American Stock Exchange-------------------");for(Stock s:list){s.show();}
System.out.println("------------------------------------------------------------------------");
}/*** 让投资人随机投资*/
public voidinvest(){
Investor inv1= new Investor("巴菲特");
Investor inv2= new Investor("索罗斯");//让投资人随机投资
for(Stock s:list){//比如巴菲特只投资价格是偶数的股票
if(Math.round(s.price)%2==0){
s.addObserver(inv1);
System.out.println(String.format("[%s]投资了[%s]:[%.2f]", inv1.name,s.symbol,s.price));
}//比如索罗斯只投资价格是3的倍数的股票
if(Math.round(s.price)%3==0){
s.addObserver(inv2);
System.out.println(String.format("[%s]投资了[%s]:[%.2f]", inv2.name,s.symbol,s.price));
}
}
}//生成随机股票
privateStock emitStock() {
StringBuilder val= newStringBuilder(); Stock s;
Random random= newRandom();for(int i = 0; i < 3; i++) {int temp = 65; //or 97
val .append((char)(random.nextInt(26) +temp));
}
s= new Stock(val.toString(),random.nextFloat()*100);returns;
}public voidshuffle(){for(Stock s:list){
s.shuffle();
}
}class Stock extendsObservable {public Stock(String symbol, floatprice) {this.symbol=symbol;this.price=price;
}public voidshow(){
System.out.println(String.format("[%s]:[%.2f]", this.symbol,this.price));
}privateString symbol;private floatprice;//价格随机波动
public voidshuffle(){this.price = this.price+new Random().nextInt(10)-5;this.setChanged();this.notifyObservers();
}
}class Investor implementsObserver{publicInvestor(String name){this.name =name;
}privateString name;
@Overridepublic voidupdate(Observable o, Object arg) {
Stock s=(Stock)o;
System.out.println(String.format("[%s]获取到[%s]的最新价格[%.2f]",this.name, s.symbol,s.price));
}
}
}