Q: How to notify Lists about order change ?
Possible case scenario not necessarily the best one.
The class car could implement the Observer design pattern. Then in each setter after, value change you could notify the listeners about it.
In the code where you are creating the list, you could add the listener to car, that check for order property change and reorder the list.
The example event
public class PropertyChangeEvent extends EventObject {
private final String propertyName;
private final Object oldValue;
private final Object newValue;
public PropertyChange(String propertyName, Object oldValue, Object newValue) {
this.propertyName = propertyName;
this.oldValue = oldValue;
this.newValue = newValue;
}
public String getProperty() {
reutnr this.propertyName;
}
//Rest of getters were omitted.
}
And the listener
public abstract interface PropertyChangeListener extends EventListener {
public abstract void propertyChange(PropertyChangeEvent event);
}
Then you should write a class that will support the property change, is should have methods like addPropertyChangeListener(PropertyChangeListener pcl), firePropertyChange(PropertyChangeEvent pce).
When the manger of property change is done. Only thing what you have to do is.
public class Car {
private PropertyChangeManager manager = new PropertyChangeManager(Car.class);
/* The omitted code*/
public void setOrder(int order) {
int oldValue = this.order;
this.order = order;
manager.firePropertyChange("order", oldValue, this.order);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
this.manager.addPropertyChangeLIstener(pcl);
}
}
And in the class where you use that list.
private SortedList<Car> sortedCars=new SortedList<Car>();
private PropertyChangeListener listReorder = new ProprtyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
if("order".equals(event.getProperty()) {
reoderCars();
}
}
public boolean addCarToOrderList(Car car) {
/* Safety code omitted */
boolean result = false;
if(sortedCars.contains(car) == false) {
result = sortedCars.add(car);
}
if(result) {
car.addPropertyChangeListener(listReorder); //We assume that this is safe
}
return result;
}
public void reoderCars() {
synchronized(this.sortedCar) {
//the code that will sort the list.
}
}