Let's say I have a function Farm (animal1, animal2, ...)
that takes objects as parameters. These objects are either sheep or cows, which are made by one of two factory methods:
function Sheep(id)
{
function noise() {console.log('baa');}
return {
my_id : id,
noise
}
}
function Cow(id)
{
function noise() {console.log('moo');}
function swish_tail () {}
return {
my_id : id,
noise,
swish_tail
}
}
Now, imagine Farm
needs to do something different depending on the type of object of each animal (e.g. just list the numbers of each, or perhaps make all the sheep make a noise first then the cows). What is the best thing to do?
- Use prototypes for each animal, and check the prototype of each in Farm?
- Work based on the knowledge that only a
Cow
has aswish_tail ()
function as a member? - Have
Sheep
andCow
functionally inherit from anAnimal
factory method, and add something like atype
member toAnimal
?
Ideally, Farm
should be ignorant of the implementation of each animal as far as possible,
Edit: I understand there are similarities with this question however this does not quite address the question of how to solve the specific problem.