將物件組織成樹狀結構、『部分-全體』層級關係,讓外界以一致性的方式對待個別物件和整體物件。
class Component
# @return [Component]
def parent
@parent
end
def parent=(parent)
@parent = parent
end
def add(component)
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
def remove(component)
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
def composite?
false
end
def operation
raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
end
end
class Leaf < Component
def operation
'Leaf'
end
end
class Composite < Component
def initialize
@children = []
end
def add(component)
@children.append(component)
component.parent = self
end
def remove(component)
@children.remove(component)
component.parent = nil
end
def composite?
true
end
def operation
results = []
@children.each { |child| results.append(child.operation) }
"Branch(#{results.join('+')})"
end
end
def client_code(component)
puts "RESULT: #{component.operation}"
end
def client_code2(component1, component2)
component1.add(component2) if component1.composite?
print "RESULT: #{component1.operation}"
end
simple = Leaf.new
puts 'Client: I\'ve got a simple component:'
client_code(simple)
puts "\n"
tree = Composite.new
branch1 = Composite.new
branch1.add(Leaf.new)
branch1.add(Leaf.new)
branch2 = Composite.new
branch2.add(Leaf.new)
tree.add(branch1)
tree.add(branch2)
puts 'Client: Now I\'ve got a composite tree:'
client_code(tree)
puts "\n"
puts 'Client: I don\'t need to check the components classes even when managing the tree:'
client_code2(tree, simple)
Client: I've got a simple component:
RESULT: Leaf
Client: Now I've got a composite tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf))
Client: I don't need to check the components classes even when managing the tree:
RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)+Leaf)
可以將整個設計概念想成是節點(Composite
)與端點(Leaf
),節點可以包涵端點或者節點,的是端點就不包含其他東西。而多個節點(Composite
)組合,可以變成一個tree
當然也可以想成盒子(Composite
),內容物則可能包含更多盒子(Composite
)與產品(Leaf
),而外部最大的盒子,就是一個tree
文章不定期更新!
感謝大家 如有問題,再煩請大家指教!