源码索引 / CURRENT IMPLEMENTATION
learning/go-patterns/stages/02-dependencies/main.go
54 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。
跳到函数 / 声明
// Stage 02 keeps the service independent from a particular price source.
// Run it with: go run .
package main
import "fmt"
type Price struct {
Item string
Cents int
}
// PriceSource is defined by the service that consumes it. The interface is
// deliberately small: this service only needs one lookup operation.
type PriceSource interface {
Lookup(item string) (Price, error)
}
// Catalog is one production implementation of PriceSource.
type Catalog map[string]Price
func (c Catalog) Lookup(item string) (Price, error) {
price, ok := c[item]
if !ok {
return Price{}, fmt.Errorf("item %q is not in the catalog", item)
}
return price, nil
}
type Service struct {
source PriceSource
}
func NewService(source PriceSource) Service {
return Service{source: source}
}
// Quote depends on behavior, not on Catalog's representation.
func (s Service) Quote(item string) (Price, error) {
return s.source.Lookup(item)
}
func main() {
service := NewService(Catalog{
"book": {Item: "book", Cents: 2100},
"pen": {Item: "pen", Cents: 300},
})
price, err := service.Quote("book")
if err != nil {
fmt.Println("quote failed:", err)
return
}
fmt.Printf("%s: %d cents\n", price.Item, price.Cents)
}