Jam*_*hon 9 java web-applications javabeans observer-pattern
我注意到有些人写bean支持Property Change观察者模式.
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
public class SampleBean implements Serializable {
public static final String PROP_SAMPLE_PROPERTY = "sampleProperty";
private String sampleProperty;
private PropertyChangeSupport propertySupport;
public ChartBean() {
propertySupport = new PropertyChangeSupport(this);
}
public String getSampleProperty() {
return sampleProperty;
}
public void setSampleProperty(String value) {
String oldValue = sampleProperty;
sampleProperty = value;
propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY, oldValue, sampleProperty);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我记得由于Web应用程序的无状态特性,观察者模式并不常用于基于Web的MVC模式.
在Web应用程序 Java bean中遵循上述模式是一种好习惯吗?
Gar*_*vis 10
老实说,如果你真的需要这个功能,那就太麻烦了.大多数Web应用程序不需要PropertyChangeSupport.我实际上不记得看到它被用在我见过的任何网络应用程序中.我只看到它被用于Swing应用程序.
beanWeb应用程序中的典型是一个非常短暂的对象,准备为单个请求提供服务,然后转入void以进行垃圾回收.主要的问题是Web应用程序是我的自然并发和多用户,这不会让自己适应具有监听器和事件等的长寿对象.