将一个方法与一个返回”self”的结构体关联起来。

huangapple go评论86阅读模式
英文:

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;
}

huangapple
  • 本文由 发表于 2014年2月23日 02:04:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/21958229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定