손 훑 기 golang 구조 설계 원칙 개폐 원칙
발단
최근 디자인 모드 복습 담 용 덕 의 < > 이 책 은 자바 언어 로 흔 한 디자인 모드 를 연 기 했 습 니 다.
개폐 원칙
장면
사고의 방향
ICourse.go
principles/open_close / ICourse. go 과정 인터페이스
package open_close
type ICourse interface {
ID() int
Name() string
Price() float64
}
GolangCourse.go
principles/open_close / Golang Course. gogolang 과정 류, 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
}
IDiscount.go
principles/open_close / IDiscount. go 할인 인터페이스
package open_close
type IDiscount interface {
Discount() float64
}
DiscountedGolangCourse.go
principles/open_close / Discounted Golang Course. 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()
}
open_close_test.go
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
", 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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.