-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcash.go
More file actions
120 lines (102 loc) · 2.34 KB
/
Copy pathcash.go
File metadata and controls
120 lines (102 loc) · 2.34 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
package ch2
import (
"fmt"
"math"
)
type CashStrategyer[T float64 | int64] interface {
CalculateCash() T
}
// CashSuper
type CashSuper[T float64 | int64] struct {
amount T
price T
}
// CashNormal
type CashNormal[T float64 | int64] struct {
CashSuper[T]
}
func (c *CashNormal[T]) New(amount, price T) {
c.price = price
c.amount = amount
}
func (c *CashNormal[T]) CalculateCash() T {
return c.amount * c.price
}
// CashRebate
type CashRebate[T float64 | int64] struct {
CashSuper[T]
rebate float64 //rebate
}
func (c *CashRebate[T]) New(amount, price T, reba float64) {
c.rebate = reba
c.price = price
c.amount = amount
}
func (c *CashRebate[T]) CalculateCash() T {
return c.amount * c.price * T(c.rebate)
}
// CashReturn
type CashReturn[T float64 | int64] struct {
CashSuper[T]
moneyCondition T
moneyReturn T
}
func (c *CashReturn[T]) New(moneyCondition, moneyReturn, amount, price T) {
c.moneyCondition = moneyCondition
c.moneyReturn = moneyReturn
c.price = price
c.amount = amount
}
func (c *CashReturn[T]) CalculateCash() T {
money := c.amount * c.price
var result T
if c.moneyCondition <= money {
result = money - T(math.Floor(float64(money/c.moneyCondition)))*c.moneyReturn
}
return result
}
// context
type CashContext[T float64 | int64] struct {
strategy CashStrategyer[T]
}
func NewCashContext[T float64 | int64](strtegy CashStrategyer[T]) *CashContext[T] {
context := new(CashContext[T])
context.strategy = strtegy
return context
}
func (this *CashContext[T]) GetCashResult() T {
return this.strategy.CalculateCash()
}
func (this *CashContext[T]) CashContextFactory(conType string) {
switch conType {
case "Normal":
cn := &CashNormal[T]{}
cn.New(10, 3)
this.strategy = cn
case "Rebate":
cn := &CashRebate[T]{}
cn.New(10, 3, 0.8)
this.strategy = cn
}
}
func CashRun() {
cn := &CashNormal[float64]{}
cn.New(10, 3)
context := NewCashContext[float64](cn)
res := context.strategy.CalculateCash()
fmt.Println("Normal:", res)
cr := &CashRebate[float64]{}
cr.New(10, 3, 0.8)
context = NewCashContext[float64](cr)
res = context.strategy.CalculateCash()
fmt.Println("Rebate:", res)
//strategy+simplyfactory
const (
NORMAL = "Normal"
REBATE = "Rebate"
)
contextNormal := new(CashContext[float64])
contextNormal.CashContextFactory(NORMAL)
res = contextNormal.GetCashResult()
fmt.Println("Normal 2:", res)
}