I'm learning and trying to implement the Observer pattern in Java from this tutorial. I'm stuck at the point about whether I should use WeakReference
for the subject to hold the observers.
For the implementation below, the Subject
and the BinaryObserver
are holding strong references to each other, which I'm afraid prevents GC from collecting the unused Subject
.
So my question is, should I use List<WeakReference<Observer>> observers
instead of List<Observer> observers
?
Subject.java
public class Subject {
private List<Observer> observers = new ArrayList<Observer>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyAllObservers();
}
public void attach(Observer observer){
observers.add(observer);
}
public void notifyAllObservers(){
for (Observer observer : observers) {
observer.update();
}
}
}
Observer.java
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
BinaryObserver.java
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println("Binary String: " + Integer.toBinaryString());
}
}
ObserverPatternDemo.java
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new BinaryObserver(subject);
System.out.println("First state change: 15");
subject.setState(15);
}
}
Aucun commentaire:
Enregistrer un commentaire