golang结构体使用接口组合
我有一个可以使用不同服务注册的雷格,我想根据传递的服务访问儿童方法 - 搜索。由于这些方法很常见,因此我想使用单个探测器并根据服务动态访问该方法。我已经使用了结构构图,并将服务作为父母,这在其他两个服务中。问题是我将服务作为Newproductservice和NeworderService中的接口作为Apiterface和Parent Service Struct在Regester中搜索。但是默认情况下,调用了基于父母服务的搜索,我希望它调用实际基于服务的搜索。
package main
import "fmt"
type APIService interface {
Search() string
Regester(prefix string)
}
type service struct {
}
func (p *service) Regester(prefix string) {
fmt.Println(prefix, "register")
s := p.Search()
fmt.Println(s)
}
func (p *service) Search() string {
return "parent search"
}
type OrderService struct {
service
}
type ProductService struct {
service
}
func NewProductService() APIService {
fmt.Println("reached prod service")
return &ProductService{}
}
func NewOrderService() APIService {
fmt.Println("reached order service")
return &OrderService{}
}
func (p *ProductService) Search() string {
return "prod serach"
}
func (p *OrderService) Search() string {
return "order search"
}
func main() {
pr := NewProductService()
po := NewOrderService()
pr.Regester("products")
po.Regester("orders")
}
I have a regester which can be registered using different services, i want to access the child method - search based on the service passed. Since the methods are common i want to use a single regester and dynamically access the method based on the service. I have used struct composition and made service as parent which is in both other services. Problem is i am passing the service as interface in newProductService and newOrderService as an APIInterface and parent service struct makes the call to search in regester. But by default parent service based Search is called, i want it to call the actual service based Search.
package main
import "fmt"
type APIService interface {
Search() string
Regester(prefix string)
}
type service struct {
}
func (p *service) Regester(prefix string) {
fmt.Println(prefix, "register")
s := p.Search()
fmt.Println(s)
}
func (p *service) Search() string {
return "parent search"
}
type OrderService struct {
service
}
type ProductService struct {
service
}
func NewProductService() APIService {
fmt.Println("reached prod service")
return &ProductService{}
}
func NewOrderService() APIService {
fmt.Println("reached order service")
return &OrderService{}
}
func (p *ProductService) Search() string {
return "prod serach"
}
func (p *OrderService) Search() string {
return "order search"
}
func main() {
pr := NewProductService()
po := NewOrderService()
pr.Regester("products")
po.Regester("orders")
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论