2
votes

Instead of using built in class Observable and Observer I am trying to build it myself.

From docs I figured:

public class Observable{
   private Set<Observer> observingMe=null;
   private boolean amIchanged;

   public void notifyObservers(Object args){
        for(Observer o:observingMe){
            o.update(args);
        }
   }

   public void addObserver(Observer e){
    observingMe.add(e);
   }

}

public class Price implements Observable{
    private int price;
    public void setPrice(int newPrice){
        price=newPrice;
        notifyObservers(price);
    }
}
public interface Observer{
    public void update(Object args);
}

Is this(in brief) the right implementation of Observable? What else do I need to consider while building Observable class. Is there a way to automatically detect any chane in Observable instance or the inherited class has to explicitly call notifyObservers?

Please don't mind the syntax or minor error

3
How does Observer look like? - Wim Deblauwe
updated the Observer interface - lliB the Lizard

3 Answers

2
votes

In your notify method, consider the case when an observer throws an exception when the update is called. If you don't handle it, it will prevent the other observers the be notified. Moreover, you may want to notify each observer in a separate thread as one of them could take a long time to react to the event, preventing the others to be notified early.

Also, you never use your boolean amIChanged and you keep it private without a getter. Otherwise, you have the basic principle implemented.

0
votes

There are a few things wrong at first:

  • observingMe will give a NullPointerException when used since it is not initalized.
  • You cannot use implements with a class. You should use extends since Observable is a class.
  • amIchanged is never used. You can remove it.
0
votes

Regarding the automatic observers notification: you might want to wire an AOP after advice, triggered after each set...(...) method invocation. (check for the exact pointcut syntax).

But is it worth the effort? To make sure method notifyObservers() is invoked, you might prefer a couple of test methods.

You might also consider having a removeObserver(Observer e) method as well.