Golang Interface Pattern
Today I learn golang interface patterns from this article : https://dzone.com/articles/three-productive-go-patterns-to-put-on-your-radar, one of the interesting section is client-side interface pattern, and I wonder how it would looks for "Caller Side Interface Pattern". In this post I try to visualize and summarize it.
Client Side Interface Pattern
The idea of client-side interface pattern is to put the interface type on client package. by doing this, we only write interface once for all controllers, less freedom when writing caller code.
package controller
import "project/usecase"
func New(u usecase.Usecase) *controller {
return &controller{
u,
}
}
type controller struct{
u usecase.Usecase
}
func (c *controller) InsertData() {
c.u.InsertDataToDB()
}
package usecase
func New() Usecase {
return &usecase{}
}
type Usecase interface{
InsertDataToDB()
}
type usecase struct{}
func (u *usecase) InsertDataToDB(){
return
}
Caller Side Interface Pattern
Contrary to client-side, the caller-side interface pattern put the interface in caller package. so if we have multiple controller depend to 1 usecase. we need to write multiple interface foreach caller package. the pros of this approach is more freedom for caller package incase it need to adjust the dependency.
package controller
type Usecase interface{
InsertDataToDB()
}
func New(u Usecase) *controller {
return &controller{
u,
}
}
type controller struct{
u Usecase
}
func (c *controller) InsertData() {
c.u.InsertDataToDB()
}
package usecase
func New() usecase{
return &usecase{}
}
type usecase struct{}
func (u *usecase) InsertDataToDB(){
return
}
Komentar
Posting Komentar