回答編集履歴

2

さらに詳細な説明とサンプルコードを追加。

2015/08/04 00:10

投稿

hy3
hy3

スコア594

test CHANGED
@@ -32,7 +32,7 @@
32
32
 
33
33
 
34
34
 
35
- func newSingleton(req *http.Request) *singleton {
35
+ func newSingleton(r *http.Request) *singleton {
36
36
 
37
37
  s := new(singleton)
38
38
 
@@ -42,11 +42,11 @@
42
42
 
43
43
  }
44
44
 
45
- func GetInstance(req *http.Request) *singleton {
45
+ func GetInstance(r *http.Request) *singleton {
46
46
 
47
47
  once.Do(func() {
48
48
 
49
- instance = newSingleton(req)
49
+ instance = newSingleton(r) // <-初回呼び出し時のみここが呼ばれる
50
50
 
51
51
  })
52
52
 
@@ -58,6 +58,22 @@
58
58
 
59
59
 
60
60
 
61
+ ハンドラ側からの呼び出しコードは以下のようになります。
62
+
63
+
64
+
65
+ ```go
66
+
67
+ func SomeHandler(w http.ResponseWriter, r *http.Request) {
68
+
69
+ data := singleton.GetInstance(r)
70
+
71
+ // データを使用した処理
72
+
73
+ }
74
+
75
+ ```
76
+
61
77
  出典:
62
78
 
63
79
  Singleton Pattern in Go(英文)

1

質問内容に合わせてコードを特化させた。

2015/08/04 00:10

投稿

hy3
hy3

スコア594

test CHANGED
@@ -9,6 +9,8 @@
9
9
 
10
10
 
11
11
  import (
12
+
13
+ "net/http"
12
14
 
13
15
  "sync"
14
16
 
@@ -30,11 +32,21 @@
30
32
 
31
33
 
32
34
 
35
+ func newSingleton(req *http.Request) *singleton {
36
+
37
+ s := new(singleton)
38
+
39
+ // ここでGAEを用いてDatastoreからデータを取得する
40
+
41
+ return s
42
+
43
+ }
44
+
33
- func GetInstance() *singleton {
45
+ func GetInstance(req *http.Request) *singleton {
34
46
 
35
47
  once.Do(func() {
36
48
 
37
- instance = &singleton{}
49
+ instance = newSingleton(req)
38
50
 
39
51
  })
40
52