如何像在 Java 中一样在 Python 中编写具有观察者/可观察设施的程序?我会用Java写一些类似的东西。
import java.util.Observable;
import java.util.Observer;
public class ObservDemo extends Object {
MyView view;
MyModel model;
public ObservDemo() {
view = new MyView();
model = new MyModel();
model.addObserver(view);
}
public static void main(String[] av) {
ObservDemo me = new ObservDemo();
me.demo();
}
public void demo() {
model.changeSomething();
}
/** The Observer normally maintains a view on the data */
class MyView implements Observer {
/** For now, we just print the fact that we got notified. */
public void update(Observable obs, Object x) {
System.out.println("update(" + obs + "," + x + ");");
}
}
/** The Observable normally maintains the data */
class MyModel extends Observable {
public void changeSomething() {
// Notify observers of change
setChanged();
notifyObservers();
}
}
}
(此代码取自以下链接 http://www.java2s.com/Code/Java/Design-Pattern/AsimpledemoofObservableandObserver.htm)
我如何在 Python 中完成这样的事情?