I am working on a personal project in university where I am currently trying to make my own implementation of a generic observer pattern that I can use throughout my project.
I would appreciate any feedback, but I am specifically interested in how to generalize it further or perhaps some change that makes it even easier to use/reuse. Basically, where would this implementation break down in the future?
Below you can see my very simple test-class which works as it should. When the name of the box is updated (either through some change to the model, or through a user update from the controller) the name in the controller is also updated.
public class ObservableTest {
public static void main(String[] args) {
Box box = new Box();
BoxController boxController = new BoxController(box);
box.setBoxName("test1");
System.out.println(box.getBoxName());
System.out.println(boxController.boxName);
box.setBoxNameAlt("test2");
System.out.println(box.getBoxName());
System.out.println(boxController.boxName);
boxController.changeName("test3");
System.out.println(box.getBoxName());
System.out.println(boxController.boxName);
}
}
The box has a name, which is made into an observable by wrapping it in my Observable class. Whenever the observable is edited the update method should be called on the Observable.
public class Box {
public Observable<String> boxName = new Observable<>("hello");
public void setBoxName(String str) {
boxName.set(str);
boxName.update();
}
public String getBoxName() {
return boxName.get();
}
}
Here is my actual Observable class, which I think is self explanatory.
public class Observable<Item> {
public Item item;
private final ArrayList<Observer<Item>> observers = new ArrayList<>();
public Observable(Item item) {
this.item = item;
}
public void update() {
for (Observer<Item> o : observers) {
o.update(item);
}
}
public void set(Item item) {
this.item = item;
update();
}
public Item get() {
return item;
}
public void observe(Observer<Item> observer) {
observers.add(observer);
}
public void removeObserver(Observer<Item> observer) {
observers.remove(observer);
}
}
Here is the Observer interface.
public interface Observer<Item> {
void update(Item item);
}
And finally the controller of the box which is listening for updates of the boxes name.
public class BoxController {
private final Observable<String> boxNameObservable;
//@FXML
String boxName;
BoxController(Box box) {
boxNameObservable = box.boxName;
boxNameObservable.observe(updatedName -> boxName = updatedName);
}
public void changeName(String str) {
boxNameObservable.item = str;
boxNameObservable.update();
}
}
This is my first time posting here, so if I have done something wrong I'm happy to fix it! Thanks!