Factory pattern : Factory « Design Patterns « Ruby





Factory pattern


class Animal
  def initialize(name)
    @name = name
  end

  def eat
    puts("#{@name} is eating.")
  end

  def speak
    puts("#{@name} says !")
  end

  def sleep
    puts("#{@name} sleeps; ")
  end
end

class Zoo
  def initialize(number_animals)
    @animals = []
    number_animals.times do |i|
      animal = new_animal("Animal#{i}")
      @animals << animal
    end
  end

  def action
    @animals.each {|animal| animal.speak}
    @animals.each {|animal| animal.eat}
    @animals.each {|animal| animal.sleep}
  end
end

class AnimalZoo < Zoo
  def new_animal(name)
    Animal.new(name)
  end
end

pond = AnimalZoo.new(3)
pond.action

 










Related examples in the same category

1.Use class method to create object