Re: [問題] 一個MVC pattern和composite pattern的 …

看板Ruby作者 (godfat 真常)時間17年前 (2007/10/12 22:42), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串4/4 (看更多)
edit typo ※ 引述《jackace (inevitable......)》之銘言: : 抱歉喔 我可能沒敘述的很好 我是用ruby沒錯... : 我的結構是這樣: : class Content : end : class Section < Content : def initialize(title) : @items = Array.new : @title = title : end : end : class Text < Content : def initialize(text) : @text=text : end : end : 那個Section.items放的是任何的Content 所以可以是Section或Text : 這樣應該就是composite pattern....吧??? 我剛學DP不太確定是不是這樣叫 這個...我是覺得不是這樣說的,因為你這邊 @items 可以放 Section 或 Text, 跟 static typing 下以 interface 達到的 composite pattern 完全無關, 這邊純粹是 ruby dynamic typing 下的結果。 anyway, 名詞不重要,反正我現在知道你要做什麼了... : 那我在View 裡面要從最頂層的Section開始往下traverse : 比如說遇到Section的時候要用粗體把Section的title印出來 : 遇到Text的時候要印text : 那要怎麼避免if(instance_of?)的寫法?? 不想把 display 寫到 model 中,那考慮 visitor pattern? class DisplayVisitor def visit_section section "<strong>#{section.content}</strong>" end def visit_text text text.content end end class Content def accept visitor NotImplementedError.new 'please override this method.' end end class Section < Content def accept visitor visitor.visit_section self end end class Text < Content def acceot visitor visitor.visit_text self end end 用法就會是: Section.accept DisplayVisitor.new Section.accept FadeOutVisitor.new 諸如此類。 嫌麻煩?ruby 厲害之處就在此啦... class Content def accept visitor visitor.send "visit_#{self.class.to_s.downcase}", self end end class Section < Content; end class Text < Content; end 於是你的 display 就寫在 visitor 裡面了。 如果還是嫌不應該全部擠在 visitor 裡,再善用 mixin 吧 :p class DisplayVisitor include TextDisplayer include SectionDisplayer end 要多打很多次很煩?再來 meta-programming... 不過這次我不寫範例了 :o -- 「行け!Loki!」(rocky ロッキー) -Gurumin ぐるみん 王子? XD -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.28.18 ※ 編輯: godfat 來自: 220.135.28.18 (10/12 22:45)

10/12 23:32, , 1F
大感恩
10/12 23:32, 1F
文章代碼(AID): #173uV1JU (Ruby)
文章代碼(AID): #173uV1JU (Ruby)