It shows you how the composite pattern can be used so that different kinds of objects in a tree data structure can be treated consistently.
复合模式:
这个设计模式为你展示了不同类型的在树中的数据结构如何一致的对待。
client:
let doorWindow = CompositePart(name: "DoorWindow",parts:
Part(name: "Window",price: 100.50),
Part(name: "Window Switch",price: 12));
let door = CompositePart(name: "Door",parts:
doorWindow,
Part(name: "Door Loom",price: 80),
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();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pattern:
protocol CarPart {
var name:String { get };
var price:Float { get };
func addPart(part:CarPart) -> Void;
func removePart(part:CarPart) -> Void;
}
class Part : CarPart {
let name:String;
let price:Float;
init(name:String,price:Float) {
self.name = name; self.price = price;
}
func addPart(part: CarPart) {
// do nothing
}
func removePart(part: CarPart) {
// do nothing
}
}
class CompositePart : CarPart {
let name:String;
private var parts:[CarPart];
init(name:String,parts:CarPart...) {
self.name = name; self.parts = parts;
}
var price:Float {
return reduce(parts,0,{subtotal,part in
return subtotal + part.price;
});
}
func addPart(part:CarPart) {
parts.append(part);
}
func removePart(part:CarPart) {
for index in 0 ..< parts.count {
if (parts[index].name == part.name) {
parts.removeAtIndex(index);
break;
}
}
}
}
////
import Foundation
class CustomerOrder {
let customer:String;
let parts:[CarPart];
init(customer:String,parts:[CarPart]) {
self.customer = customer;
self.parts = parts;
}
var totalPrice:Float {
return reduce(parts,part in
return subtotal + part.price});
}
func printDetails() {
println("Order for \(customer): Cost: \(formatCurrencyString(totalPrice))");
}
func formatCurrencyString(number:Float) -> String {
let formatter = NSNumberFormatter();
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle;
return formatter.stringFromNumber(number) ?? "";
}
}