将对象组合成树形结构以表示“部分-整体”的层次结构,Composite 使得用户对单个对象和组合对象的使用具有一致性,用户可以统一地使用组合结构中的所有对象。(注:择自设计模式的黑书)
/*:
Component
*/
protocol Shape {
func draw(fillColor: String)
}
/*:
Leafs
*/
final class Square : Shape {
func draw(fillColor: String) {
print("Drawing a Square with color \(fillColor)")
}
}
final class Circle : Shape {
func draw(fillColor: String) {
print("Drawing a circle with color \(fillColor)")
}
}
/*:
Composite
*/
final class Whiteboard : Shape {
lazy var shapes = [Shape]()
init(_ shapes:Shape...) {
self.shapes = shapes
}
func draw(fillColor: String) {
for shape in self.shapes {
shape.draw(fillColor: fillColor)
}
}
}
/*:
### Usage:
*/
var whiteboard = Whiteboard(Circle(), Square())
whiteboard.draw(fillColor: "Red")