[实验任务一]:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
实验要求:
1. 画出对应类图;
2. 提交源代码;
3. 注意编程规范。
1.类图
2.源代码
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(); } } } // 观察者接口 public interface Guancha { public void sheng(); public void jiang(); } // 具体观察者类 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("股票降价了,哭了"); } } // 主类 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); } }
标签:Gumin,21,void,观察者,System,实验,println,public,out From: https://www.cnblogs.com/po3a/p/18556044