我知道 Go 没有传统的 OOP 概念。但是,我很想知道是否有更好的方法来设计“构造函数”,就像我在下面的代码片段中所做的那样:
type myOwnRouter struct {
}
func (mor *myOwnRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from my own Router!")
}
func newMyOwnRouter() *myOwnRouter {
return &myOwnRouter{}
}
func init() {
http.Handle("/", newMyOwnRouter())
...
}
我基本上想摆脱“独立”的 newMyOwnRouter() 函数并将其作为结构本身的一部分,例如我希望能够执行类似的操作:
http.Handle("/", myOwnRouter.Router)
这可行吗?
最佳答案
事实上的标准模式是一个函数调用 New
package matrix
function NewMatrix(rows, cols int) *matrix {
m := new(matrix)
m.rows = rows
m.cols = cols
m.elems = make([]float, rows*cols)
return m
}
当然构造函数必须是Public函数,才能在包外调用。
关于构造函数模式的更多信息 here
在你的情况下,你想要一个 Sigleton 包,那么这就是模式:
package singleton
type myOwnRouter struct {
}
var instantiated *myOwnRouter = nil
func NewMyOwnRouter() * myOwnRouter {
if instantiated == nil {
instantiated = new(myOwnRouter);
}
return instantiated;
}
关于go - 将方法与返回 "self"的结构相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958229/