import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
interface Subject {
public void addListener(Observer o);
public void firePropertyChange(String propertyName,
int index, Object old, Object newvalue);
}
interface Observer extends PropertyChangeListener {
}
class Calculator implements Subject {
private int fVal;
private PropertyChangeSupport fPropertyChangeSupport;
public Calculator() {
this(0);
fPropertyChangeSupport = new PropertyChangeSupport(this);
}
public Calculator(int val) {
this.fVal = val;
}
public void add(int other) {
int oldVal = fVal;
int newVal = fVal + other;
fVal = newVal;
fPropertyChangeSupport.firePropertyChange("add", oldVal, newVal);
}
public void subtract(int other) {
int oldVal = fVal;
int newVal = fVal - other;
fVal = newVal;
fPropertyChangeSupport.firePropertyChange("subtract", oldVal, newVal);
}
public void addListener(Observer o) {
fPropertyChangeSupport.addPropertyChangeListener(o);
}
public void firePropertyChange(String propertyName,
int index, Object oldValue, Object newValue) {
fPropertyChangeSupport.fireIndexedPropertyChange(propertyName,
index, oldValue, newValue);
}
}
class BoxObserver implements Observer {
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("********************************************");
System.out.println("Method: " + evt.getPropertyName());
System.out.println("Old Value: " + evt.getOldValue());
System.out.println("New Value: " + evt.getNewValue());
System.out.println("********************************************");
}
}
class OneLineObserver implements Observer {
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("In " + evt.getPropertyName() + ": " +
evt.getOldValue() + " => " + evt.getNewValue());
}
}
public class App {
public static void main(String[] args) {
Calculator calc = new Calculator();
BoxObserver box = new BoxObserver();
OneLineObserver line = new OneLineObserver();
calc.addListener(box);
calc.addListener(line);
calc.add(1);
calc.subtract(2);
}
}
Comments are welcome!
Comments 2
Constructor쪽이 약간 잘못된 것 같은데…
다음과 같이 돼야 하는 거 아닐까요?
public Calculator() {
this(0);
}
public Calculator(int val) {
this.fVal = val;
fPropertyChangeSupport = new PropertyChangeSupport(this);
}
안 그러면 constructor chain이 제대로 작동하지 않을 것 같은데…
Sam
Posted 23 May 2006 at 6:08 am ¶헉 맞아요;; 감사!! (^^)(__)
Posted 23 May 2006 at 1:24 pm ¶Post a Comment