英文:
Associating a method with a struct that returns "self"
问题
我理解Go语言没有传统的面向对象编程概念。然而,我很想知道是否有更好的方法来设计一个"构造函数",就像我在下面的代码片段中所做的那样:
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)
这样可行吗?
英文:
I understand that Go doesn't have traditional OOP concepts. However, I'd love to know whether there is a better way for designing a "constructor" as I've done it in my code snippet below:
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())
...
}
I basically would like to get rid of the "stand alone" newMyOwnRouter() function and have it as part of the struct itself, for example I'd like to be able to do something like:
http.Handle("/", myOwnRouter.Router)
Is that doable?
答案1
得分: 2
defacto标准模式是一个名为New
package matrix
func NewMatrix(rows, cols int) *matrix {
m := new(matrix)
m.rows = rows
m.cols = cols
m.elems = make([]float, rows*cols)
return m
}
当然,构造函数必须是公共的,可以在包外部调用。
关于构造函数模式的更多信息可以在这里找到。
在你的情况下,看起来你想要一个单例包,那么这就是模式:
package singleton
type myOwnRouter struct {
}
var instantiated *myOwnRouter = nil
func NewMyOwnRouter() *myOwnRouter {
if instantiated == nil {
instantiated = new(myOwnRouter)
}
return instantiated
}
英文:
The defacto standard pattern is a function calle New<struct>
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
}
Of course the construct function must be a Public one, to be called outside of the package.
More about constructor pattern here
In your case looks like you want a Sigleton package then this is the pattern:
package singleton
type myOwnRouter struct {
}
var instantiated *myOwnRouter = nil
func NewMyOwnRouter() * myOwnRouter {
if instantiated == nil {
instantiated = new(myOwnRouter);
}
return instantiated;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论