swift - The Composite Pattern

发布时间:2020-05-20 发布网站:脚本之家
脚本之家收集整理的这篇文章主要介绍了swift - The Composite Pattern脚本之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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) ?? "";

}

}

总结

以上是脚本之家为你收集整理的swift - The Composite Pattern全部内容,希望文章能够帮你解决swift - The Composite Pattern所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢交流学习经验,点击链接加入脚本之家官方QQ群:1065694478
脚本之家官方公众号

微信公众号搜索 “ 程序精选 ” ,选择关注!

微信公众号搜索 “ 程序精选 ”
精选程序员所需精品干货内容!