feat: add factory

main
ZGGSONG 2 years ago
commit 4037ea75d0

2
.gitignore vendored

@ -0,0 +1,2 @@
.idea/
.DS_Store

@ -0,0 +1,3 @@
## 说明
《大话设计模式》 代码记录

@ -0,0 +1,15 @@
package factory
func CreateCashAccept(t int) Casher {
var cash Casher
switch t {
case 1: //正常
cash = new(CashNormal)
case 2: //8折
cash = &CashRebate{moneyRebate: 0.8}
case 3: //满300减50
cash = &CashReturn{moneyCondition: 300, moneyReturn: 50}
default:
}
return cash
}

@ -0,0 +1,7 @@
package factory
type CashNormal struct{}
func (c *CashNormal) AcceptCash(money float64) float64 {
return money
}

@ -0,0 +1,11 @@
package factory
// CashRebate
// @Description: 打折收费
type CashRebate struct {
moneyRebate float64
}
func (c *CashRebate) AcceptCash(money float64) float64 {
return money * c.moneyRebate
}

@ -0,0 +1,18 @@
package factory
import "math"
// CashReturn
// @Description: 返利收费
type CashReturn struct {
moneyCondition float64
moneyReturn float64
}
func (c *CashReturn) AcceptCash(money float64) float64 {
ret := money
if money >= c.moneyCondition {
ret = money - math.Floor(money/c.moneyCondition)*c.moneyReturn
}
return ret
}

@ -0,0 +1,47 @@
package factory
import "testing"
func TestCashNormal_AcceptCash(t *testing.T) {
accept := CreateCashAccept(1)
if accept == nil {
t.Error("testing failed")
}
money := 300.0
ret := accept.AcceptCash(money)
t.Log("\t应付: ", money)
t.Log("\t实付: ", ret)
}
func TestCashRebate_AcceptCash(t *testing.T) {
accept := CreateCashAccept(2)
if accept == nil {
t.Error("testing failed")
}
money := 300.0
ret := accept.AcceptCash(money)
t.Log("\t应付: ", money)
t.Log("\t实付: ", ret)
}
func TestCashReturn_AcceptCash(t *testing.T) {
accept := CreateCashAccept(3)
if accept == nil {
t.Error("testing failed")
}
money := 300.0
ret := accept.AcceptCash(money)
t.Log("\t应付: ", money)
t.Log("\t实付: ", ret)
}
func TestCash(t *testing.T) {
accept := CreateCashAccept(4)
if accept == nil {
t.Fatal("testing failed")
}
money := 300.0
ret := accept.AcceptCash(money)
t.Log("\t应付: ", money)
t.Log("\t实付: ", ret)
}

@ -0,0 +1,5 @@
package factory
type Casher interface {
AcceptCash(money float64) float64
}

@ -0,0 +1,3 @@
module designpatterns
go 1.19
Loading…
Cancel
Save