首頁 > 後端開發 > Golang > 主體

golang 中的適配器模式

王林
發布: 2024-02-10 08:40:10
轉載
878 人瀏覽過

golang 中的适配器模式

golang中的適配器模式是一種常用的設計模式,它可以幫助我們將不相容的介面轉換為可相容的介面。透過適配器,我們可以實現不同系統、不同類別之間的互通性,提高程式碼的靈活性和多用性。 php小編香蕉將在本文中詳細介紹適配器模式的概念、應用場景以及實作方式,幫助讀者更好地理解並應用此設計模式。無論是初學者或有一定經驗的開發者,都能從本文中獲得實用的知識和技巧,加深對golang適配器模式的理解。讓我們一起來探索這個有趣又實用的設計模式吧!

問題內容

嘗試在 golang 中建立適配器模式,不確定我哪裡做錯了。我的 client.go 顯示錯誤

#c.broker.placeorder 未定義(類型 exchange.exchange 沒有欄位或方法 placeorder)

main.go

package main

import (
    "context"
    "oms/consumer"
)

func main() {
    ctx := context.background()
    consumer.consumer(ctx)
}
登入後複製

消費者.go

package consumer

import (
    "context"
    "fmt"
    "oms/broker"
)

func consumer(ctx context.context) {
    broker.execute()
}
登入後複製

client.go

package broker

import (
    "oms/broker/exchange"
)
type client struct {
    broker exchange.exchange
}

func (c *client) setbroker(broker exchange.exchange) {
    c.broker = broker
}

func (c *client) placeorder(id string, quantity, price int) {
// i am getting error here
    c.broker.placeorder(id, quantity, price)
}
登入後複製

經紀人.go

package broker

// create a client and set its broker to paytm
import (
    "oms/broker/paytm"
)

func execute() {
    client := &client{}
    client.setbroker(paytm.paytm{ /* fields */ })
    client.placeorder("order1", 10, 100)
}
登入後複製

exchange.go

package exchange

type exchange interface {
    placeorder(id string, quantity, price int)
}
登入後複製

paytm.go

package paytm

import "oms/broker/exchange"

type Paytm struct {
    // fields
}

func (p Paytm) placeOrder(id string, quantity, price int) {
    // implementation for Paytm's placeOrder method
}
登入後複製

解決方法

您正嘗試從 broker 套件中呼叫未匯出的方法。 如果您想從 paytm 套件外部呼叫該方法,您應該在您的介面以及您的方法中將其重命名為 PlaceOrder

有關導出/未導出字段和方法的更多信息,請參見此處:https://golangbyexample.com/exported-unexported-fields-struct-go /

#

以上是golang 中的適配器模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!