Go設(shè)計模式之模板方法模式講解和代碼示例
Go 模板方法模式講解和代碼示例
模版方法是一種行為設(shè)計模式, 它在基類中定義了一個算法的框架, 允許子類在不修改結(jié)構(gòu)的情況下重寫算法的特定步驟。
概念示例
讓我們來考慮一個一次性密碼功能 (OTP) 的例子。 將 OTP 傳遞給用戶的方式多種多樣 (短信、 郵件等)。 但無論是短信還是郵件, 整個 OTP 流程都是相同的:
- 生成隨機的 n 位數(shù)字。
- 在緩存中保存這組數(shù)字以便進行后續(xù)驗證。
- 準備內(nèi)容。
- 發(fā)送通知。
后續(xù)引入的任何新 OTP 類型都很有可能需要進行相同的上述步驟。
因此, 我們會有這樣的一個場景, 其中某個特定操作的步驟是相同的, 但實現(xiàn)方式卻可能有所不同。 這正是適合考慮使用模板方法模式的情況。
首先, 我們定義一個由固定數(shù)量的方法組成的基礎(chǔ)模板算法。 這就是我們的模板方法。 然后我們將實現(xiàn)每一個步驟方法, 但不會改變模板方法。
otp.go: 模板方法
package main
type IOtp interface {
genRandomOPT(int) string
saveOPTCache(string)
getMessage(string) string
sendNotification(string) error
}
type Otp struct {
iOtp IOtp
}
func (o *Otp) genAndSendOPT(optLength int) error {
opt := o.iOtp.genRandomOPT(optLength)
o.iOtp.saveOPTCache(opt)
message := o.iOtp.getMessage(opt)
if err := o.iOtp.sendNotification(message); err != nil {
return err
}
return nil
}sms.go: 具體實施
package main
import (
"fmt"
)
type Sms struct {
Otp
}
func (s *Sms) genRandomOPT(len int) string {
randomOTP := "1234"
fmt.Printf("SMS: generating random otp %s \n", randomOTP)
return randomOTP
}
func (s *Sms) saveOPTCache(otp string) {
fmt.Printf("SMS: saving otp %s", 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
}email.go: 具體實施
package main
import (
"fmt"
)
type Email struct {
Otp
}
func (s *Email) genRandomOPT(len int) string {
randomOTP := "2345"
fmt.Printf("Email: generating random otp %s \n", randomOTP)
return randomOTP
}
func (s *Email) saveOPTCache(otp string) {
fmt.Printf("Email: saving otp %s to cache", 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
}main.go: 客戶端代碼
package main
import "fmt"
func main() {
smsOTP := &Sms{}
o := Otp{
iOtp: smsOTP,
}
o.genAndSendOPT(4)
fmt.Println("")
emailOtp := &Email{}
o = Otp{
iOtp: emailOtp,
}
o.genAndSendOPT(4)
}output.txt: 執(zhí)行結(jié)果
SMS: generating random otp 1234
SMS: saving otp 1234SMS: sending sms: SMS OTP for login is 1234Email: generating random otp 2345
Email: saving otp 2345 to cacheEmail: sending email Email otp for login is 2345
到此這篇關(guān)于Go設(shè)計模式之模板方法模式講解和代碼示例的文章就介紹到這了,更多相關(guān)Go模板方法模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go?io/fs.FileMode文件系統(tǒng)基本操作和權(quán)限管理深入理解
這篇文章主要為大家介紹了Go?io/fs.FileMode文件系統(tǒng)基本操作和權(quán)限管理深入理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
一文詳解如何在Golang中實現(xiàn)JWT認證與授權(quán)
在現(xiàn)代Web應用中,安全性是一個非常重要的課題,JWT作為一種常用的認證與授權(quán)機制,已被廣泛應用于各種系統(tǒng)中,下面我們就來看看如何在Golang中實現(xiàn)JWT認證與授權(quán)吧2025-03-03

