Skip to content

Instantly share code, notes, and snippets.

@dich1
Last active September 21, 2019 01:48
Show Gist options
  • Save dich1/5607610bd0b5798fe6e54367e822529b to your computer and use it in GitHub Desktop.
Save dich1/5607610bd0b5798fe6e54367e822529b to your computer and use it in GitHub Desktop.
Factory Method(ファクトリーメソッド)パターン ref: https://qiita.com/dich1/items/78e625378725f2f881a1
require './SuperCreator'
class Main
creator = SuperCreator.new(:name1 => '製品1', :name2 => '製品2')
creator.factory_method()
end
require './SuperCreator'
class Main
creator = SuperCreator.new(:name1 => '製品1', :name2 => '製品2')
creator.factory_method()
end
require './SuperProduct'
class SubProduct1 < SuperProduct
def initialize(product1)
super
end
def abstract_method()
puts "#{@product}の特徴1"
end
end
require './SuperProduct'
class SubProduct2 < SuperProduct
def initialize(product2)
super
end
def abstract_method()
puts "#{@product}の特徴2"
end
end
require './SubProduct1'
require './SubProduct2'
class SuperCreator
def initialize(args)
@product1 = new_product(:type1, args[:name1])
@product2 = new_product(:type2, args[:name2])
end
def factory_method()
@product1.template_method()
@product2.template_method()
end
def new_product(type name)
return SubProduct1.new(name) if type == :type1
return SubProduct2.new(name) if type == :type2
raise "Unknown product type #{type}"
end
end
class SuperProduct
def initialize(product)
@product = product
end
def template_method()
abstract_method()
end
def abstract_method()
raise 'Abstract method'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment