Skip to content

Instantly share code, notes, and snippets.

@kasei-san
Created July 26, 2014 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kasei-san/42f8063d8f991bda5900 to your computer and use it in GitHub Desktop.
Save kasei-san/42f8063d8f991bda5900 to your computer and use it in GitHub Desktop.
Abstruct Factorty パターン ref: http://qiita.com/kasei-san/items/97d43cce70ab087294ae
# ファイルを生成して、upload するという流れ
class FileUploader # Client
def initialize(factory)
@file_maker = factory.file_maker
@uploader = factory.uploader
end
def make_flie(items)
@file = file_maker.make(item)
end
def upload
uploader.upload(@file)
end
end
class FileUploaderFactory # AbstructFactory
def file_maker
raise NotImplementedError
end
def uploader
raise NotImplementedError
end
end
class CsvFileScpUploderFactory < FileUploaderFactory # ConcreteFactory
def file_maker
@file_maker ||= CsvFileMaker.new # ConcreteProduct
end
def uploader
@uploader ||= ScpUploder.new # ConcreteProduct
end
end
class HttpFileFtpUploderFactory < FileUploaderFactory # ConcreteFactory
def file_maker
@file_maker ||= HttpFileMaker.new # ConcreteProduct
end
def uploader
@uploader ||= FtpUploder.new # ConcreteProduct
end
end
# FileUploader は、どの ConcreteProduct を使って処理を行うかを、AbstructFactory のサブクラスに任せている
file_uploader = FileUploader.new(CsvFileScpUploderFactory.new) # CSV を SCP で upload
file_uploader.make_flie(%w[abc def])
file_uploader.upload
file_uploader = FileUploader.new(HttpFileFtpUploderFactory.new) # HTTP を FTP で upload
file_uploader.make_flie(%w[abc def])
file_uploader.upload
# 新しい処理が必要になったら、ConcreteFactory、ConcreteProduct を増やせばよいだけ
関連するインスタンス群を生成するための API を集約することによって、複数のモジュール群の再利用を効率化することを目的とする
class FileUploader
def initialize(file_maker_name, uploader_name)
@file_maker = Object.const_get("#{file_maker_name.to_s.capitalize}FileMaker").new
@uploader = Object.const_get("#{file_maker_name.to_s.capitalize}Uploader").new
end
...
FileUploader.new(:http, :ftp) # HTTP を FTP で upload
FileUploader.new(:csv, :scp) # CSV を SCP で upload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment