Subject/Observer 패턴의 구현

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!

Similar Posts:

Comments 2