-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathContents.swift
108 lines (87 loc) · 2.37 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 协议
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())
}
cc.getResult(200)
// 策略模式与简单工厂模式结合
var cs = CashContextWithSimpleFactoryPattern(.byDefault)
cs.getResult(100)
cs = CashContextWithSimpleFactoryPattern(.twentyPersentOff)
cs.getResult(200.5)
cs = CashContextWithSimpleFactoryPattern(.every300Get100Return)
cs.getResult(650)