定义:
将对象组合成树形结构以表示“部分-整体”的层次结构。 组合使得用户对单个对象和组合对象的使用具体一致性。
- 结构性模式
- 使用于树形结构
案例
class Part {
let name: String;
let price: Float;
init(name: String, price: Float) {
self.name = name;
self.price = price;
}
}
class CompositePart {
let name: String;
let parts: [Part];
init(name: String, parts: Part...) {
self.name = name;
self.parts = parts;
}
}
class CustomerOrder {
let customer: String;
let parts: [Part];
let compositeParts: [CompositePart];
init(customer: String, parts: [Part], composites: [CompositePart]) {
self.customer = customer;
self.parts = parts;
self.compositeParts = composites;
}
var totalPrice :Float {
let partReducer = { (subtotal: Float, part: Part)-> Float in
return subtotal + part.price;
};
let total = parts.reduce(0, partReducer);
return compositeParts.reduce(total){ (subtotal, cpart) -> Float in
return cpart.parts.reduce(subtotal, partReducer);
};
}
func printDetails() {
print("Oreder for \(customer): Cost: \(totalPrice)");
}
}
let doorWindow = CompositePart(name: "DoorWindow",parts:
Part(name: "Window", price: 100.50),
Part(name: "Window Switch", price: 12));
let door = CompositePart(name: "Door", parts:
Part(name: "Window", price: 100.50),
Part(name: "Door Loom", price: 80),
Part(name: "Window Switch", price: 12),
Part(name: "Door Handles", price: 43.40))
let hood = Part(name: "Hood", price: 320);
let order = CustomerOrder(customer: "Bob", parts: [hood], composites: [door, doorWindow]);
order.printDetails();
组合模式 重构
protocol CartPart {
var name: String { get };
var price: Float { get };
}
class Part : CartPart {
let name: String;
let price: Float;
init(name: String, price: Float) {
self.name = name;
self.price = price;
}
}
class CompositePart : CartPart {
let name: String;
let parts: [CartPart];
init(name: String, parts: CartPart...) {
self.name = name;
self.parts = parts;
}
var price: Float {
return parts.reduce(0, { (subtotal, part) in
return subtotal + part.price;
});
}
}
class CustomerOrder {
let customer: String;
let parts: [CartPart];
init(customer: String, parts: [CartPart]) {
self.customer = customer;
self.parts = parts;
}
var totalPrice :Float {
return parts.reduce(0, { (subtoal, part) in
return subtoal + part.price;
})
}
func printDetails() {
print("Oreder for \(customer): Cost: \(totalPrice)");
}
}
let doorWindow = CompositePart(name: "DoorWindow",parts:
Part(name: "Window", price: 100.50),
Part(name: "Window Switch", price: 12));
let door = CompositePart(name: "Door", parts:
Part(name: "Window", price: 100.50),
Part(name: "Door Loom", price: 80),
Part(name: "Window Switch", price: 12),
Part(name: "Door Handles", price: 43.40))
let hood = Part(name: "Hood", price: 320);
let order = CustomerOrder(customer: "Bob", parts: [hood, door, doorWindow]);
order.printDetails();
总结
- 这个模式主要是找到“部分”
- 要有好的封装能力