为什么没有通知观察员?

时间:2014-04-09 12:44:14

标签: java swing design-patterns observer-pattern

我正在尝试在Java Swing应用程序中实现观察者模式我正在研究我的学校项目。我有这两个非常简单的类,一个状态是单例可观察模型,第二个是观察者。

可观察模型:

public class Model extends Observable {

    private static Model instance = null;
    private File selectedImageFile;
    private int colorsCount;

    public static Logger LOG = Logger.getLogger(Model.class);

    private Model() {
        this.initialize();
    }

    private void initialize() {
        addObserver(new ModelObserver());
    }

    public static Model instance() {
        if (Model.instance == null) {
            Model.instance = new Model();
        }
        return Model.instance;
    }

    public void setColorsCount(int colorsCount) {
        this.colorsCount = colorsCount;
        notifyObservers(Actions.COLORS_COUNT);
    }

    public void selectedImage(File imageFile) {
        this.selectedImageFile = imageFile;
        notifyObservers(Actions.SELECTED_IMAGE);
    }

    public enum Actions {
        SELECTED_IMAGE, COLORS_COUNT
    }

}

观察

public class ModelObserver implements Observer {

    public static Logger LOG = Logger.getLogger(ModelObserver.class);

    @Override
    public void update(Observable o, Object arg) {

        if (arg instanceof Model.Actions) {

            Model.Actions action = (Actions) arg;

            switch (action) {

            case SELECTED_IMAGE:
                selectedImage();
                break;

            case COLORS_COUNT:
                colorsCount();
                break;

            default:
                LOG.warn("Not supported action: " + action);
                break;
            }

        } else {
            LOG.warn("Not supported action: " + String.valueOf(arg));
        }

    }

    private void colorsCount() {
        LOG.info("Colors count has been changed....");
    }

    private void selectedImage() {
        LOG.info("Image has been changed....");
    }

}

一切正常 - 模型实例注册更改但观察者(在我的情况下只有一个)不会得到通知。在方法ModeObserver.update(Observable o, Object arg)中,没有提到模型已被更改。所以我的问题是没有通知观察者。

我做错了什么?谢谢。

1 个答案:

答案 0 :(得分:3)

您忘记致电setChanged()将可观察对象标记为已更改,这是notifyObservers实际执行通知所必需的。