iOS Swift 5.2 设计模式

Swift 5.2 Builder Pattern 建造者模式

2020-07-08  本文已影响0人  Sunooo

复杂的对象,有很多种属性,不想把属性完全暴露给外界,这时候就可以用建造者设计模式,一步一步的给对象属性赋值,生成对象。
过生日,办婚礼,都可能需要买蛋糕。
假设这家蛋糕店提供了三种风格的蛋糕,
生日蛋糕,婚礼蛋糕,冰激凌蛋糕,
可以添加多种水果,有苹果,香蕉,橙子,草莓,
可以选购多种蜡烛,数字样式,ins样式的,烟花样式的
顾客在买蛋糕的时候,不需要知道蛋糕具体是怎么做的,只需要告诉蛋糕师傅(CakeBuilder)要那种蛋糕,需要哪些配料,就可以了。
蛋糕制作出来之后,顾客也不能更改蛋糕的配料了,Cake的属性都是let型,不可变的。

public class Cake {
    public let fruit: Fruit
    public let style: Style
    public let candle: Candle
    
    public init(fruit: Fruit, style: Style, candle: Candle) {
        self.fruit = fruit
        self.style = style
        self.candle = candle
    }
}


public enum Style: String {
    case birthday
    case wedding
    case iceCream
}

public struct Fruit: OptionSet {
    public static let apple =  Fruit(rawValue: 1 << 0)
    public static let banana = Fruit(rawValue: 1 << 1)
    public static let orange = Fruit(rawValue: 1 << 2)
    public static let strawberry = Fruit(rawValue: 1 << 3)
    
    public let rawValue: Int
    public init(rawValue: Int) {
        self.rawValue = rawValue
    }
}


public struct Candle: OptionSet {
    public static let number =  Candle(rawValue: 1 << 0)
    public static let ins = Candle(rawValue: 1 << 1)
    public static let fireworks = Candle(rawValue: 1 << 2)
    
    public let rawValue: Int
    public init(rawValue: Int) {
        self.rawValue = rawValue
    }
}


public class CakeBuilder {
    public private(set) var style: Style = .birthday
    public private(set) var fruits: Fruit = []
    public private(set) var candles: Candle = []
    
    public func addFruit(_ fruit: Fruit) {
        self.fruits.insert(fruit)
    }
    
    public func removeFruit(_ fruit: Fruit) {
        self.fruits.remove(fruit)
    }
    
    public func addCandle(_ candle: Candle) {
        self.candles.insert(candle)
    }
    
    public func removeCandle(_ candle: Candle) {
        self.candles.remove(candle)
    }
    
    public func setStyle(_ style: Style) {
        self.style = style
    }
    
    public func build() -> Cake {
        return Cake(fruit: fruits, style: style, candle: candles)
    }
    
}

public class Customer {
    func bookBirthdayStrawberryCake() -> Cake {
        let builder = CakeBuilder()
        builder.setStyle(.birthday)
        builder.addFruit(.strawberry)
        builder.addCandle([.number, .fireworks])
        return builder.build()
    }
    
    func bookWeddingInsCake() -> Cake {
        let builder = CakeBuilder()
        builder.setStyle(.wedding)
        builder.addFruit([.apple, .banana, .orange, .strawberry])
        builder.addCandle(.ins)
        return builder.build()
    }
}



let xiaoMing = Customer()
let cake = xiaoMing.bookWeddingInsCake()
上一篇下一篇

猜你喜欢

热点阅读