classHouse defphrase(number) data.last(number).join('') end
defline(number) "This is #{phrase(number)}.\n" end
defrecite (1..data.length).map { |i| lin(i)}.join("\n") end
defdata [ 'This is the house that Jack built.' 'This is the malt that lay in the house that Jack built.' 'This is the rat that ate the malt,' 'That lay in the house that Jack built.' 'This is the cat that chased the rat,' 'That ate the malt that lay in the house that Jack built.' 'This is the dog that worried the cat,' 'That chased the rat that ate the malt,' 'That lay in the house that Jack built.' ] end end
classHouse defdata [ 'This is the house that Jack built.' 'This is the malt that lay in the house that Jack built.' 'This is the rat that ate the malt,' 'That lay in the house that Jack built.' 'This is the cat that chased the rat,' 'That ate the malt that lay in the house that Jack built.' 'This is the dog that worried the cat,' 'That chased the rat that ate the malt,' 'That lay in the house that Jack built.' ] end end
classRandomHouse < House defdata @data ||= super.shuffle end end # 改成 classHouse DATA = [ 'This is the house that Jack built.' 'This is the malt that lay in the house that Jack built.' 'This is the rat that ate the malt,' 'That lay in the house that Jack built.' 'This is the cat that chased the rat,' 'That ate the malt that lay in the house that Jack built.' 'This is the dog that worried the cat,' 'That chased the rat that ate the malt,' 'That lay in the house that Jack built.' ]
defdata @data ||= DATA end end
classRandomHouse < House defdata @data ||= DATA.shuffle end end
使用表格來做思考,然後什麼改變了就給他一個名字
class
data
???
House
DATA
RandomHouse
DATA
shuffle
這裡的 ??? 應該填入什麼呢?往他上一層抽象來想的話,比較準確的應該是 order
class
data
order!
House
DATA
RandomHouse
DATA
shuffle
這時候再重新問一次上面的問題:
Is Order a House?
明顯不是,那 Order 是什麼呢?他其實比較接近一個角色(role),可以說是功能型球員,我們根據這樣的概念來改寫:
1 2 3 4 5 6 7 8 9 10
classDefaultOrder deforder(data) data end end classRandomOrder deforder(data) data.shuffle end end
我們現在需要的是把排序的相依從 House 裡面拿出來
首先改寫一下 House
1 2 3 4 5 6 7
classHouse DATA = [...] attr_reader:data definitialize @data = Data end end
然後把對 order 的相依性放進去
1 2 3 4 5 6 7
classHouse DATA = [...] attr_reader:data definitialize(orderer = DefaultOrder.new) @data = orderer.order(DATA) end end
這裡的概念就是把不同的東西抽出來,做成 pluggable behavior 的樣子
更精簡來說:
Inject an object to play the role of the thing that varies
defparts(number) formatter.format(data.last(number)) end end classDefaultFormatter defformat(parts) parts end end classEchoFormatter defformat(parts) parts.zip(parts).flatten end end puts House.new(formatter: EchoFormatter.new).line(12)