软件设计模式————(观察者模式)
[实验任务一]:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
实验要求:
1. 画出对应类图;
2. 提交源代码;
package org.example;
import java.util.ArrayList;
public class Fen{
private ArrayList<Guancha> oblist;
public Fen(){
oblist=new ArrayList<>();
}
public void add(Guancha a){
oblist.add(a);
}
public void remove(Guancha a){
oblist.remove(a);
}
public void sheng(double a){
if(a>0.05)
for(Guancha guan:oblist){
guan.sheng();
}
}
public void jiang(double a){
if(a>0.05)
for(Guancha guan:oblist){
guan.jiang();
}
}
}
package org.example;
public class Gumin implements Guancha{
private String name;
public Gumin(String a){name=a;}
public void sheng(){
System.out.println(name+"买了一些股票(股票升了)");
}
public void jiang(){
System.out.println("股票降价了,哭了");
}
}
package org.example;
public class main {
public static void main(String[] args) {
Fen f=new Fen();
Gumin g1=new Gumin("第一个股民");
Gumin g2=new Gumin("第二个股民");
f.add(g1);
f.add(g2);
System.out.println("股票升了");
f.sheng(0.1);
System.out.println("比率小于0.05");
System.out.println();
f.sheng(0.001);
System.out.println("股票降了");
f.jiang(0.1);
System.out.println("比率小于0.05");
System.out.println();
f.jiang(0.001);
}
}
package org.example;
public interface Guancha {
public void sheng();
public void jiang();
}