# Create a basic organism.
puts "I'm a basic organism"
# Derive an organism that modifies the speak method.
class OrganismOther < Organism
puts "I'm another organism"
# Create a "factory" that take a Class as a parameter and can
# generate organisms of that class.
@organism_class = organism_class
if __FILE__ == $PROGRAM_NAME
# Create a basic and other factory for the two types of organisms.
organism_factory_basic = OrganismFactory.new(Organism)
organism_factory_other = OrganismFactory.new(OrganismOther)
# Generate an organism of each type.
organism = organism_factory_basic.generate_organism
organism_other = organism_factory_other.generate_organism
# Let them speak.
You can see that we create a basic Organism and then subclass it to get a slightly different organism. There's nothing too awfully interesting there. Next is the OrganismFactory where we show off our new technique. The
initialize()method takes a Class as a parameter and saves it away in the
@organism_classvariable. We also have a method
generate_organism()that will return an object of the type that was passed in. Finally, we have the main program that creates a couple of factories, one of each type, and then uses them to create objects of each type. Finally, we make sure they work by having them "speak".
Let me know if you have questions or comments on this.