mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-22 11:56:03 +03:00
add new pattern
This commit is contained in:
parent
512f18568a
commit
df83749126
14
creation/25_new/REDME.md
Normal file
14
creation/25_new/REDME.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
# New pattern
|
||||||
|
|
||||||
|
New 模式
|
||||||
|
|
||||||
|
最最最简单,最最最常用的模式。
|
||||||
|
|
||||||
|
以至于很多地方都不把它当成模式,都已经熟悉到了被忽略的地步,我觉得这是不公平的:),要恢复它地位。
|
||||||
|
|
||||||
|
New模式是就是使用类似New()/new()/NewXXX()之类的方法,返回一个实现了某个接口的对象的引用。
|
||||||
|
|
||||||
|
须要注意的是的:
|
||||||
|
|
||||||
|
+ 一定是返回 结构对象的地址(引用)
|
||||||
|
+ 该结构对象往往返回一个实现了某接口的方法.
|
28
creation/25_new/new_test.go
Normal file
28
creation/25_new/new_test.go
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
package newpattern
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
type homecat interface {
|
||||||
|
sleep()
|
||||||
|
}
|
||||||
|
|
||||||
|
type blackCat struct {
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newBlackCat(name string) homecat{
|
||||||
|
return &blackCat{name}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
func (b blackCat) sleep() {
|
||||||
|
fmt.Print( b.name + " is sleeping")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewMode(t *testing.T){
|
||||||
|
|
||||||
|
cat := newBlackCat("pi")
|
||||||
|
cat.sleep()
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user