定義:
將對(duì)象組合成樹(shù)形結(jié)構(gòu)以表示“部分-整體”的層次結(jié)構(gòu)。 組合使得用戶(hù)對(duì)單個(gè)對(duì)象和組合對(duì)象的使用具體一致性。
- 結(jié)構(gòu)性模式
- 使用于樹(shù)形結(jié)構(gòu)
案例
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();
組合模式 重構(gòu)
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();
總結(jié)
- 這個(gè)模式主要是找到“部分”
- 要有好的封裝能力