类图
源码
Observer.java package com.demo; public interface Observer { public void moneyUp(); public void moneyDown(); } Subject.java package com.demo; import java.util.ArrayList; public abstract class Subject { protected ArrayList<Observer> olist=new ArrayList<>(); public Subject() { // TODO Auto-generated constructor stub } public void add(Observer o) { olist.add(o); } public void remove(Observer o) { olist.remove(o); } public abstract void up(double a); public abstract void down(double a); } GuMin.java package com.demo; public class GuMin implements Observer{ private String name; public GuMin(String n) { // TODO Auto-generated constructor stub name=n; } @Override public void moneyUp() { // TODO Auto-generated method stub System.out.println(name+"买了一些股票(股票升了)"); } @Override public void moneyDown() { // TODO Auto-generated method stub System.out.println(name+"股票降价了,哭了"); } } GuPiao.java package com.demo; public class GuPiao extends Subject{ public GuPiao() { // TODO Auto-generated constructor stub } /* * public void add(Observer o) { super.add(o); } */ public void up(double a) { // TODO Auto-generated method stub if(a>0.05) for(Observer gum : olist){ gum.moneyUp();; } } public void down(double a) { // TODO Auto-generated method stub if(a>0.05) for(Observer gum:olist){ gum.moneyDown();; } } } Client.java package com.demo; public class Client { public static void main(String[]args) { // TODO Auto-generated constructor stub Subject f=new GuPiao(); GuMin g1=new GuMin("股民A"); GuMin g2=new GuMin("股民B"); f.add(g1); f.add(g2); System.out.println("股票升了"); f.up(0.1); System.out.println("比率小于0.05"); System.out.println(); f.down(0.001); System.out.println("股票降了"); f.down(0.1); System.out.println("比率小于0.05"); f.down(0.001); } }
测试截图