Swift門面模式VS函數式

文章來自:cocochina

/*
    第一種通過類的門面模式
 */

class Dish: CustomStringConvertible {
    var name: String ;
    var price: Int ;
    init(name: String, price: Int) {
        self.name = name;
        self.price = price;
    }
    
    var description: String{
        get {
            return "\(name): \(price)元"
        }
    }
}

class DishOrder{
    func append(dash:Dish){
        
    }
    func total() -> Int {
        return 1;
    }
}

class SaltDishDecorator: Dish {
    init(dish: Dish) {
        super.init(name: "加糖 \(dish.name)", price: dish.price + 1)
    }
}


/*
    通過協議 擴展組合模式
 */

protocol Product {
    var name: String {get set}
    var price: Int {get set}
}

protocol Salteable: Product {
    func salted() -> Self
}

extension Salteable{
    func salted() -> Self {
        var newProduct = self ;
        newProduct.name = "加鹽\(name)" ;
        newProduct.price = price + 1 ;
        return newProduct ;
    }
}

struct Snack: CustomStringConvertible {
    var name: String ;
    var price: Int ;
    init(name: String, price: Int) {
        self.name = name ;
        self.price = price ;
    }
    var description: String{
        get{
            return "\(name): \(price)元"
        }
    }
}

extension Snack: Salteable{
    
}
最后的結果更優雅
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容