There's more than one way to do things | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
A recurring pattern that occurs is that you want to construct instances from a class hierarchy based on some typeless data (eg, deserializing a string).
Taking a typical barnyard example:
A new animal wanders into your program and identifies itself with a noise. Either "baa", "moo" or "oink". You could do this:
The problem is that each time you define a new animal, you have to update your make_animal function. What would be better is if within the class somehow the animal "registered" itself against the sound it makes. We can do that by creating a global hash, and then each animal class enters itself into this hash:
And then the make_animal function becomes:
This function then would not change when a new Animal is added to the hierarchy. Can anyone recommend any ways of cleaning this up? Is there a more elegant way of doing what I am trying to do? Without using BEGIN blocks and a global hash perhaps? Or without breaking any strictures? Is there a CPAN module that does something similiar to this? -Andrew. In reply to Factory Pattern by tomazos
|
|