Observer? design pattern

design-patterns, observer-pattern

Solution

The Observer design pattern could possibly be used to solve your problem. In the Observer Pattern, there are two distinct types of objects:

- Observer objects are objects that want to be notified whenever Observable objects change.

- Observable objects are objects that can be watched by Observers

Observers are registered with the Observable objects they wish to watch. Whenever an Observable object changes, it notifies all of the Observers that have been registered with it.

Based on your code example I am going to assume you are using Java. In that case you can use Observer and Observable to reduce the number of changes you have to make to your existing code.

public class mammal extends java.util.Observable implements Imammle
{

    public String getName() {
        return "Mammal";
    }

    public String speak() {
        setChanged(); // We have been changed
        notifyObservers(); // Notify everyone that we have changed
        return getName() +  "Maaaauuu";
    }

}

Now we create a class that wishes to watch for when something changes:

public class Watcher implements java.util.Observer
{
    public void update(Observable o, Object arg) {
        System.out.println("Something has changed");
    }
}

Finally, we register our watcher(s) with a `mammal` so that they can be informed whenever it changes.

public class Main
{
    public static void main(String args[]) {
        mammal cow = new mammal();
        Watcher farmer = new Watcher();
        cow.addObserver(farmer);
        cow.speak();
    }
}

There are a number of draw-backs to this approach:

- Observers can be registered with any Observable object. You may wish for your Observer to only be able to observe `mammal`s. On the flip side, you may wish for only certain kinds of Observers to be able to observe a `mammal`.

- There really isn't any way for your `Observer` to know what exactly changed with the `mammal` without

- The `mammal` passing in some kind of message to the Observer using the notifyObservers(Object arg) method

- OR the Observer checking a public flag set in the `mammal`

If either of these drawbacks is a problem for you, then you may want to avoid `Observer` and `Observable` and look into modifying your existing classes (`mammal` and whatever your `Observers` are) to implement their own, application-specific methods.

Problem

I have ``` public class mammal implements Imammle { public String getName() { return "Mammal"; } public String speak() { return getName() + "Maaaauuu"; } } ``` I need to know when my animal makes a sound so that I can take corresponding actions in real time like eat feed. What kind of design pattern should I use? Thanks.

Original source