I noticed that some people write beans with support for the Property Change observer pattern.
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);
}
}
However, I remember reading that observer pattern is not commonly used in web based MVC patterns, due to the stateless nature of web applications.
Is it a good practice to follow the above pattern in web application Java beans?
It manages a list of listeners and dispatches PropertyChangeEvent s to them. You can use an instance of this class as a member field of your bean and delegate these types of work to it. The PropertyChangeListener can be registered for all properties or for a property specified by name.
JavaBeans is a portable, platform-independent model written in Java Programming Language. Its components are referred to as beans. In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps in accessing these object from multiple places.
To be honest only bother if you are actually going to need the feature. Most web applications don't need PropertyChangeSupport
. I can't actually remember seeing it being used in any web app that I've seen. I've only seen it being used a Swing application.
A typical bean
in a web application is a pretty short lived object, prepared to service the single request and then cast off in to the void to be garbage collected. The main issue is that web applications are my there nature concurrent and multi user this doesn't lend it self to longer lived objects with listeners and events etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With