Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

My Blog

从此烟雨落金城,一人撑伞两人行。

Go 设计模式

工厂设计模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main

type an interface{
eat()
call()
}

type cat struct{
name string
}

type dog struct{
name string
}

func (*cat)eat(){
fmt.Println("cat eat")
}
func (*cat)call(){
fmt.Println("cat call")
}
func (*dog)eat(){
fmt.Println("dog eat")
}
func (*dog)call(){
fmt.Println("dog call")
}

func fun(i int) an {
if i == 1 {
return &cat{}
} else {
return &dog{}
}
}
// 多态 向上转型
func main(){
cat := fun(1)
cat.eat()
cat.call()

dog := fun(2)
dog.eat()
dog.call()
}

```

> 将实现接口的对象赋值与接口变量

### 单例设计模式

一个类只有一个对象实例

```go
package main

import (
"fmt"
"sync"
)

type Sing interface {
do()
}

type some struct {
}

func (*some) do() {
fmt.Println("do some")
}

var (
once sync.Once
s *some
)
func Fun() Sing {
once.Do(
func() {
s = &some{}
},
)
return s
}

func main() {
s1 := Fun()
fmt.Printf("s1: %p\n", s1)
s2 := Fun()
fmt.Printf("s1: %p\n", s2)
}

抽象工厂模式

构建者模式

评论