-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
118 lines (97 loc) · 2.39 KB
/
template.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"fmt"
"math/rand"
)
/*
The Template Method pattern is a behavioral design pattern that defines the framework of an algorithm in a superclass,
allowing subclasses to override specific steps of the algorithm without modifying the structure.
1. algorithm interface contains several steps
2. make concrete algorithm
3. client owns an algorithm which can be initialized with different instances
4. client calls algorithm.run()
*/
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
//algorithm in steps
type iOtp interface {
genRandomOTP(int) string
saveOTPCache(string)
getMessage(string) string
sendNotification(string) error
publish()
}
//complete algorithm
type otp struct {
iOtp iOtp
}
func (o *otp) genAndSendOTP(otpLength int) error {
otp := o.iOtp.genRandomOTP(otpLength)
o.iOtp.saveOTPCache(otp)
message := o.iOtp.getMessage(otp)
if err := o.iOtp.sendNotification(message); err != nil {
return err
}
o.iOtp.publish()
return nil
}
//concrete algorithm realize 1
type sms struct {
otp
}
func (s *sms) genRandomOTP(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
fmt.Printf("SMS: generating random otp %v\n", b)
return string(b)
}
func (s *sms) saveOTPCache(otp string) {
fmt.Printf("SMS: saving otp: %s to cache\n", otp)
}
func (s *sms) getMessage(otp string) string {
return "SMS OTP for login is " + otp
}
func (s *sms) sendNotification(message string) error {
fmt.Printf("SMS: sending sms: %s\n", message)
return nil
}
func (s *sms) publish() {
fmt.Printf("SMS: publishing \n")
}
type email struct {
otp
}
func (s *email) genRandomOTP(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
fmt.Printf("EMAIL: generating random otp %v\n", b)
return string(b)
}
func (s *email) saveOTPCache(otp string) {
fmt.Printf("EMAIL: saving otp: %s to cache\n", otp)
}
func (s *email) getMessage(otp string) string {
return "EMAIL OTP for login is " + otp
}
func (s *email) sendNotification(message string) error {
fmt.Printf("EMAIL: sending email: %s\n", message)
return nil
}
func (s *email) publish() {
fmt.Printf("EMAIL: publishing \n")
}
func RunTemplate() {
smsOTP := &sms{}
emailOTP := &email{}
o := otp{
iOtp: smsOTP,
}
o.genAndSendOTP(4)
o = otp{
iOtp: emailOTP,
}
o.genAndSendOTP(5)
}