相关类图
具体代码
//Observer.java
package org.example.test019;
public interface Observer {
public void buy();
public void cry();
}
//Subject.java
package org.example.test019;
import java.util.ArrayList;
public abstract class Subject {
protected ArrayList<Observer> observers = new ArrayList();
public Subject() {
observers = new ArrayList<>();
}
public void attach(Observer observer) {
observers.add(observer);
}
public void detach(Observer observer) {
observers.remove(observer);
}
public abstract void up();
public abstract void down();
}
//GuFen.java
package org.example.test019;
import javax.swing.*;
public class GuFen extends Subject {
@Override
public void up() {
System.out.println("股份上涨5%");
for (Observer guan : observers) {
guan.buy();
}
}
@Override
public void down() {
System.out.println("股份下降5%");
for (Observer guan : observers) {
guan.cry();
}
}
}
//GuMin.java
package org.example.test019;
public class GuMin implements Observer {
private String name;
public GuMin(String name) {
this.name = name;
}
@Override
public void buy() {
System.out.println("股民" + name + "买了一些股票");
}
@Override
public void cry() {
System.out.println("股民" + name + "大哭一场");
}
}
//Main.java
package org.example.test019;
public class Main {
public static void main(String[] args) {
GuMin g1 = new GuMin("张三");
GuMin g2 = new GuMin("李四");
GuFen f = new GuFen();
f.attach(g1);
f.attach(g2);
f.up();
f.down();
}
}