golang结构体使用接口组合

发布于 2025-01-19 17:34:27 字数 1209 浏览 5 评论 0原文

我有一个可以使用不同服务注册的雷格,我想根据传递的服务访问儿童方法 - 搜索。由于这些方法很常见,因此我想使用单个探测器并根据服务动态访问该方法。我已经使用了结构构图,并将服务作为父母,这在其他两个服务中。问题是我将服务作为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文