1 回答

TA貢獻1875條經驗 獲得超3個贊
關于您的代碼的一些內容
根據評論中的討論,我想分享一些經驗。
我沒有看到你的解決方案有什么不好的,但是改進它的選項很少,這取決于你想做什么。
你的代碼看起來像經典的工廠。這是一種模式,它基于一些輸入參數創建單個族的對象。Factory
在Golang中,這通常以更簡單的方式用作,有時稱為。Factory MethodFactory function
例:
type Vehicle interface {};
type Car struct {}
func NewCar() Vehicle {
return &Car{}
}
但是您可以輕松擴展它以執行類似您的操作:
package main
import (
"fmt"
"strings"
)
type Vehicle interface {}
type Car struct {}
type Bike struct {}
type Motorbike struct {}
// NewDrivingLicenseCar returns a car for a user, to perform
// the driving license exam.
func NewDrivingLicenseCar(drivingLicense string) (Vehicle, error) {
switch strings.ToLower(drivingLicense) {
case "car":
return &Car{}, nil
case "motorbike":
return &Motorbike{}, nil
case "bike":
return &Bike{}, nil
default:
return nil, fmt.Errorf("Sorry, We are not allowed to make exam for your type of car: \"%s\"", drivingLicense)
}
}
func main() {
fmt.Println(NewDrivingLicenseCar("Car"))
fmt.Println(NewDrivingLicenseCar("Tank"))
}
上面的代碼產生輸出:
&{} <nil>
<nil> Sorry, We are not allowed to make exam for your type of car: "Tank"
因此,也許您可以通過以下方式改進代碼:
關閉到單個函數中,該函數采用 a 并生成
string
Response object
添加一些驗證和錯誤處理
給它一些合理的名字。
與工廠相關的模式很少,可以替換此模式:
責任鏈
調度
游客
依賴注入
反射?
@icza也有關于反射的評論。我同意他的觀點,這是常用的,我們無法避免代碼中的反射,因為有時事情是如此動態。
但在你的場景中,這是一個糟糕的解決方案,因為:
您丟失了編譯時類型檢查
添加新類型時必須修改代碼,那么為什么不在此 Factory 函數中添加新行呢?
你使代碼變慢(參見參考),它增加了50%-100%的性能損失。
你讓你的代碼如此不可讀和復雜
您必須添加更多的錯誤處理,以涵蓋反射帶來的不小錯誤。
當然,您可以添加大量測試來涵蓋大量場景。您可以在代碼中支持 、,并且可以使用測試來覆蓋它,但是在生產代碼中,有時您可以通過,如果不捕獲它,您將收到運行時錯誤。TypeA
TypeB
TypeC
TypeXYZ
結論
你的方案沒有什么不好的,這可能是做你想做的事情的最容易讀和最簡單的方法。switch/case
參考
工廠方法:https://www.sohamkamani.com/golang/2018-06-20-golang-factory-patterns/
關于編程模式的經典書籍:設計模式:可重用面向對象軟件的元素,ISBN:978-0201633610
Erich Gamma and his band of four
反射基準:https://gist.github.com/crast/61779d00db7bfaa894c70d7693cee505
- 1 回答
- 0 關注
- 127 瀏覽
添加回答
舉報