觀察者模式git
public interface IObserver { void update(); }
public class ObserverA implements IObserver { @Override public void update() { System.out.println("ObserverA update ..."); } } public class ObserverB implements IObserver { @Override public void update() { System.out.println("ObserverB update ..."); } }
public class Subject { List<IObserver> observerList = new ArrayList<>(); public void addObserver(IObserver observer){ if(!observerList.contains(observer)){ observerList.add(observer); } } public void change (){ System.out.println("Subject change ..."); notifyObservers(); } public void notifyObservers(){ for(IObserver observer : observerList){ observer.update(); } } }
public static void main(String[] args) { Subject subject = new Subject(); IObserver observerA = new ObserverA(); IObserver observerB = new ObserverB(); subject.addObserver(observerA); subject.change(); subject.addObserver(observerB); subject.change(); }
Subject change ... ObserverA update ... Subject change ... ObserverA update ... ObserverB update ...
https://github.com/Seasons20/DisignPattern.git