# Abstract Factoryパターン # # Java言語で学ぶデザインパターンと同様の例題をRubyで記述した。 # # coded by Takehiro Kaga # class Item def initialize(caption) @caption = caption end def makeHTML # abstruct method end end class Link < Item def initialize(caption, url) super(caption) @url = url end end class Tray < Item def initialize(caption) @tray = Array.new super(caption) end def add(item) @tray.push(item) end end class Page def initialize(title, author) @title = title @author = author @content = Array.new end def add(item) @content.push(item) end def output filename = @title + ".HTML" @file = File.open(filename, "w") @file.puts(self.makeHTML) # Pageを継承したクラスのmakeHTMLを使う @file.close puts filename + " を作成しました。" end def makeHTML # abstruct method end end class Factory def initialize @factory = nil end def getFactory(classname) @factory = eval(classname + ".new") end def createLink(caption, url) # abstruct method end def createTray(caption) # abstruct method end def createPage(title, author) # abstruct method end end class ListFactory < Factory def createLink(caption, url) ListLink.new(caption, url) end def createTray(caption) ListTray.new(caption) end def createPage(title, author) ListPage.new(title, author) end end class ListLink < Link def initialize(caption, url) @caption = caption @url = url super(@caption, @url) end def makeHTML "
  • " + @caption + "
  • \n" end end class ListTray < Tray def initialize(caption) @caption = caption super(@caption) end def makeHTML @buffer = "" @buffer += "
  • \n" @buffer += @caption + "\n" @buffer += "\n" @buffer += "
  • \n" @buffer end end class ListPage < Page def initialize(title, author) @title = title @author = author super(@title, @author) end def makeHTML @buffer = "" @buffer += "" + @title + "\n" @buffer += "\n" @buffer += "

    " + @title + "

    \n" @buffer += "\n" @buffer += "
    " + @author + "
    " @buffer += "\n" @buffer end end #--------------------------------------------------------------- factory = Factory.new.getFactory("ListFactory") asahi = factory.createLink("朝日新聞", "http://www.asahi.com/") yomiuri = factory.createLink("読売新聞", "http://www.yomiuri.co.jp/") us_yahoo = factory.createLink("Yahoo!", "http://www.yahoo.com/") jp_yahoo = factory.createLink("Yahoo!Japan", "http://www.yahoo.co.jp/") excite = factory.createLink("Excite", "http://www.excite.com/") google = factory.createLink("Google", "http://www.google.com/") traynews = factory.createTray("新聞") traynews.add(asahi) traynews.add(yomiuri) trayyahoo = factory.createTray("Yahoo!") trayyahoo.add(us_yahoo) trayyahoo.add(jp_yahoo) traysearch = factory.createTray("サーチエンジン") traysearch.add(trayyahoo) traysearch.add(excite) traysearch.add(google) page = factory.createPage("LinkPage", "加賀赳寛") page.add(traynews) page.add(traysearch) page.output #--------プログラムはここまで------------------------------ リターン http://www.ceres.dti.ne.jp/~kaga/