最近复习设计模式
拜读谭勇德的<<设计模式就该这样学>>
该书以java语言演绎了常见设计模式
本系列笔记拟采用golang练习之
principles/open_close/ICourse.go
课程接口
package open_close type ICourse interface { ID() int Name() string Price() float64 }
principles/open_close/GolangCourse.go
golang课程类, 实现ICourse接口
package open_close type GolangCourse struct { iID int sName string fPrice float64 } func NewGolangCourse(id int, name string, price float64) ICourse { return &GolangCourse{ iID: id, sName: name, fPrice: price, } } func (me *GolangCourse) ID() int { return me.iID } func (me *GolangCourse) Name() string { return me.sName } func (me *GolangCourse) Price() float64 { return me.fPrice }
principles/open_close/IDiscount.go
折扣接口
package open_close type IDiscount interface { Discount() float64 }
principles/open_close/DiscountedGolangCourse.go
该课程同时实现ICourse和IDiscount接口
package open_close type DiscountedGolangCourse struct { GolangCourse fDiscount float64 } func NewDiscountedGolangCourse(id int, name string, price float64, discount float64) ICourse { return &DiscountedGolangCourse{ GolangCourse: GolangCourse{ iID: id, sName: name, fPrice: price, }, fDiscount : discount, } } // implements IDiscount.Discount func (me *DiscountedGolangCourse) Discount() float64 { return me.fDiscount } // overwrite ICourse.Price func (me *DiscountedGolangCourse) Price() float64 { return me.fDiscount * me.GolangCourse.Price() }
main/open_close_test.go
课程接口测试用例
package main import ( "testing" ) import (ocp "learning/gooop/principles/open_close") func Test_open_close(t *testing.T) { fnShowCourse := func(it ocp.ICourse) { t.Logf("id=%v, name=%v, price=%v\n", it.ID(), it.Name(), it.Price()) } c1 := ocp.NewGolangCourse(1, "golang课程", 100) fnShowCourse(c1) c2 := ocp.NewDiscountedGolangCourse(2, "golang优惠课程", 100, 0.6) fnShowCourse(c2) }
$> go test -v main/open_close_test.go === RUN Test_open_close open_close_test.go:10: id=1, name=golang课程, price=100 open_close_test.go:10: id=2, name=golang优惠课程, price=60 --- PASS: Test_open_close (0.00s) PASS ok command-line-arguments 0.001s
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。