특정 메서드가 외부패키지인 billingService에 의존적인 구조
Bill 구조체는 선언 시점에 billingService를 주입받아야 하기 때문에, billingService에 의존적인 구조를 갖게됨
type Bill struct {
price int
productName string
billingService billing.Service
}
func NewBill(price, productName string, billingService billing.Service) Bill {
return Bill {
price: price,
productName: productName,
billingService: billingService
}
}
func (b Bill) Billing() (err error) {
return b.billingService.Billing(b.price, b.productName)
}
private interface를 활용해 외부패키지와 상관 없이 동작하도록 함. billingService는 외부에서 주입할 수 있다.
type Bill struct {
price int
productName string
}
func NewBill(price, productName string) Bill {
return Bill {
price: price,
productName: productName
}
}
type billerFromOutside interface {
Billing(price int, productName string) error
}
func (b Bill) Billing(biller billerFromOutside) (err error) {
return biller.Billing(b.price, b.productName)
}
type IamportBiller struct {
accessToken string
secretToken string
}
func NewIamportBiller(accessToken, secretToken string) IamportBiller {
return IamportBiller {
accessToken: accessToken,
secretToken: secretToken,
}
}
func (b IamportBiller) Billing(price int, productName string) (err error) {
// iamport에 결제하는 로직....
return err
}
type NicepayBiller struct {
accessToken string
secretToken string
}
func NewNicepayBiller(accessToken, secretToken string) NicepayBiller {
return NicepayBiller {
accessToken: accessToken,
secretToken: secretToken,
}
}
func (b NicepayBiller) Billing(price int, productName string) (err error) {
// nicepay 결제하는 로직
return err
}
func main() {
// iamport Biller
iBiller := NewIamportbiller("abc", "xyz")
// nicepay Biller
nBiller := NewNicepayBiller("abc", "xyz")
price := 500
productName := "휴지"
productBill := Bill{price, productName}
// bill with iamport
productBill.Billing(iBiller)
// bill with nicepay
productBill.Billing(nBiller)
}