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.
The Observer design pattern could possibly be used to solve your problem. In the Observer Pattern, there are two distinct types of objects:
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:
mammal
s. On the flip side, you may wish for only certain kinds of Observers to be able to observe a mammal
.Observer
to know what exactly changed with the mammal
without
mammal
passing in some kind of message to the Observer using the notifyObservers(Object arg) methodmammal
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.
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