Design-Pattern

Run Settings
LanguageSwift
Language Version
Run Command
//: Playground - noun: a place where people can play protocol CashSuper { func acceptCash(_ money: Double) -> Double } struct CashNormal: CashSuper { func acceptCash(_ money: Double) -> Double { return money } } struct CashRebate: CashSuper { let monenyRebate: Double init(_ moneyRebate: Double) { self.monenyRebate = moneyRebate } func acceptCash(_ money: Double) -> Double { return money * monenyRebate } } struct CashReturn: CashSuper { let moneyCondition: Double let moneyReturn: Double init(_ moneyCondition: Double, _ moneyReturn: Double) { self.moneyCondition = moneyCondition self.moneyReturn = moneyReturn } func acceptCash(_ money: Double) -> Double { var result = money if result >= moneyCondition { result = money - Double(Int(money / moneyCondition)) * moneyReturn } return result } } enum DiscountWays { case byDefault, twentyPersentOff, every300Get100Return } struct CashContext { private let cs: CashSuper init(_ cs: CashSuper) { self.cs = cs } func getResult(_ money: Double) -> Double { return cs.acceptCash(money) } } struct CashContextWithSimpleFactoryPattern { private let cs: CashSuper init(_ type: DiscountWays) { switch type { case .twentyPersentOff: cs = CashRebate(0.8) case .every300Get100Return: cs = CashReturn(300, 100) default: cs = CashNormal() } } func getResult(_ money: Double) -> Double { return cs.acceptCash(money) } } // 策略模式 var type = DiscountWays.twentyPersentOff var cc: CashContext switch type { case .twentyPersentOff: cc = CashContext(CashRebate(0.8)) case .every300Get100Return: cc = CashContext(CashReturn(300, 100)) default: cc = CashContext(CashNormal()) } print(cc.getResult(200)) var cs = CashContextWithSimpleFactoryPattern(.byDefault) print(cs.getResult(100)) cs = CashContextWithSimpleFactoryPattern(.twentyPersentOff) print(cs.getResult(200.5)) cs = CashContextWithSimpleFactoryPattern(.every300Get100Return) print(cs.getResult(650))
Editor Settings
Theme
Key bindings
Full width
Lines