Skip to content

Commit 16ea47d

Browse files
author
tensor-programming
committed
decorator pattern
1 parent 012864e commit 16ea47d

File tree

2 files changed

+82
-5
lines changed

2 files changed

+82
-5
lines changed

decorator/main.go

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"math"
7+
"os"
8+
"sync"
9+
"time"
10+
)
11+
12+
type piFunc func(int) float64
13+
14+
// logger(cache(Pi(n)))
15+
func wraplogger(fun piFunc, logger *log.Logger) piFunc {
16+
return func(n int) float64 {
17+
fn := func(n int) (result float64) {
18+
defer func(t time.Time) {
19+
logger.Printf("took=%v, n=%v, result=%v", time.Since(t), n, result)
20+
}(time.Now())
21+
22+
return fun(n)
23+
}
24+
return fn(n)
25+
}
26+
}
27+
28+
// cache(logger(Pi(n)))
29+
func wrapcache(fun piFunc, cache *sync.Map) piFunc {
30+
return func(n int) float64 {
31+
fn := func(n int) float64 {
32+
key := fmt.Sprintf("n=%d", n)
33+
val, ok := cache.Load(key)
34+
if ok {
35+
return val.(float64)
36+
}
37+
result := fun(n)
38+
cache.Store(key, result)
39+
return result
40+
}
41+
return fn(n)
42+
}
43+
}
44+
45+
func Pi(n int) float64 {
46+
ch := make(chan float64)
47+
48+
for k := 0; k <= n; k++ {
49+
go func(ch chan float64, k float64) {
50+
ch <- 4 * math.Pow(-1, k) / (2*k + 1)
51+
}(ch, float64(k))
52+
}
53+
54+
result := 0.0
55+
for k := 0; k <= n; k++ {
56+
result += <-ch
57+
}
58+
59+
return result
60+
}
61+
62+
func divide(n int) float64 {
63+
return float64(n / 2)
64+
}
65+
66+
func main() {
67+
f := wrapcache(Pi, &sync.Map{})
68+
g := wraplogger(f, log.New(os.Stdout, "Test ", 1))
69+
70+
g(100000)
71+
g(20000)
72+
g(100000)
73+
74+
f = wrapcache(divide, &sync.Map{})
75+
g = wraplogger(f, log.New(os.Stdout, "Divide ", 1))
76+
77+
g(10000)
78+
g(2000)
79+
g(10)
80+
g(10000)
81+
82+
}

main.go

-5
This file was deleted.

0 commit comments

Comments
 (0)