Last active
December 20, 2015 21:08
-
-
Save chinmo/6195212 to your computer and use it in GitHub Desktop.
http://morizyun.github.io/blog/ruby-design-pattern-14-abstract-factory/ を読んで考えた。 Client のインスタンスが ConcreteFactory に Product の生成を委ねるという形で捉え直した。つまり、 * Client ... 好みの ConcreteFactory (FlagAndAlgaeFactory or DuckAndWaterLilyFactory) で望みの生態系をつくる。個人的には Client が Pond だと良さそう。 * AbstractFactory ... Pond ではなく、OrganismFactory としてみた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Product 1 | |
class Frog | |
def initialize(name) | |
@name = name | |
end | |
def eat | |
puts "カエル #{@name} は食事中です" | |
end | |
end | |
# Product 2 | |
class Algae | |
def initialize(name) | |
@name = name | |
end | |
def grow | |
puts "藻 #{@name} は成長中です" | |
end | |
end | |
# Abstract Factory | |
class OrganismFactory | |
attr_reader :animals, :plants | |
def initialize(number_animals, number_plants) | |
@animals = [] | |
# 池の動物を定義する | |
number_animals.times do |i| | |
animal = new_animal("動物 #{i}") | |
@animals << animal | |
end | |
@plants = [] | |
# 池の植物を定義する | |
number_plants.times do |i| | |
plant = new_plant("植物 #{i}") | |
@plants << plant | |
end | |
end | |
private | |
def new_animal(name) | |
end | |
def new_plant(name) | |
end | |
end | |
# Concrete Factory | |
class FlogAndAlgaeFactory < OrganismFactory | |
private | |
def new_animal(name) | |
Frog.new(name) | |
end | |
def new_plant(name) | |
Algae.new(name) | |
end | |
end | |
# Client | |
# (多分 Pond#simulate_now とかで記述するのが良い) | |
FlogAndAlgaeFactory.new(2,3).animals.each { |animal| animal.eat } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment