Java接口可观察 [英] Java Interface Observable

查看:135
本文介绍了Java接口可观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:


  1. Java类:ClassA实现Observer

  1. A Java class: ClassA implements Observer

Java接口:Inter(扩展Observable,不可能)

A Java Interface: Inter (extends Observable, not possible)

Java类:ClassB实现Inter扩展Observable

A Java class: ClassB implements Inter extends Observable

Java类:ClassC实现Inter扩展Observable

A Java class: ClassC implements Inter extends Observable

现在ClassA的代码有点像这样。

Now the code for ClassA is somewhat like this.

ClassA{
    Inter anyClass = new ClassB();
           //or it could be
    Inter anyClass = new ClassC();
    //Inter.addObserver(this); //not possible since Interface cannot extend Observable
}

现在如果特定事件发生在ClassB或ClassC,我希望ClassA知道它。我想过使用Observer / Observable,但问题是Interface无法扩展Observable。

Now if a particular event happens in ClassB or ClassC, I want ClassA to know about it. I thought of using the Observer/Observable but the problem is that the Interface cannot extend Observable.

如果有人理解了这个问题,请帮我找到在ClassB或ClassC中发生更新时更新ClassA的方法。

If someone understands the question please help me find a way to update ClassA when something happens in ClassB or ClassC.

推荐答案

您不必特别使用内置的Observer / Observable java实现。您可以创建自己的接口以使用观察者模式。

You don't specifically have to use the built-in Observer/Observable java implementation. You can create your own interfaces to use the observer pattern.

使用方法'update'或'notify'(或类似的东西)创建一个接口Observer用于ClassA

Create an interface Observer with the method 'update' or 'notify' (or something like that) which will be used for ClassA

然后使用'Inter'接口充当Observable,确保它实现以下内容:

then to use the 'Inter' interface to act as an Observable make sure it implements the following:

- registerObserver(Observer)
- unregisterObserver(Observer)
- notifyObservers() //(or updateObservers(), which calls the update/notify method for all registered observers)

确保实现'Inter'接口的类也有一个名为observerCollection的arraylist跟踪观察者。然后,每当ClassB或ClassC中的某些内容发生变化,并且您想告诉ClassA(观察者),您可以调用notifyObservers()让它知道某些内容已经发生变化。

Make sure classes that implement the 'Inter' interface also have an arraylist called observerCollection to keep track of the observers. Then everytime something changes in ClassB or ClassC and you want to tell ClassA (the observer) you can call notifyObservers() to let it know something has changed.

看一看在这里看看观察者设计模式会发生什么: http://en.wikipedia.org /wiki/File:Observer.svg

Take a look at this to see what happens with the observer design pattern: http://en.wikipedia.org/wiki/File:Observer.svg

这篇关于Java接口可观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆