Go design pattern Template approach pattern explanation and code examples
Go Template methodPattern explanation and code examples
A template method is a behavioral design pattern that defines the framework of an algorithm in a base class, allowing subclasses to rewrite specific steps of the algorithm without modifying the structure.
Conceptual example
Let's consider an example of a one-time password function (OTP). There are many ways to deliver OTP to the user (SMS, email, etc.). But whether it's SMS or email, the entire OTP process is the same:
- Generates random N-digit numbers.
- Save this set of numbers in the cache for subsequent validation.
- Prepare the content.
- Send a notification.
Any new OTP type introduced later will most likely require the same steps as described above.
So we have a scenario where the steps for a particular operation are the same, but the implementation may be different. This is the case when it is appropriate to consider using the template method pattern.
First, we define a base template algorithm consisting of a fixed number of methods. This is our template approach. We will then implement each step method without changing the template method.
otp.go: template method
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: Specific implementation
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: Specific implementation
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: client code
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: indicates the execution result
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
To this article on the Go design pattern template method pattern explanation and code examples of the article is introduced to this, more related to Go template method pattern content please search script home previous articles or continue to browse the following related articles hope that you will support script home in the future!
- GoJs connection drawing template Link use example detail
- Django view layer and template layer examples detailed
- In-depth analysis of Go template template usage details
- Go design pattern strategy pattern explanation and code examples
- Go design mode state mode illustrated in detail
- Go design pattern state pattern explanation and code examples
Related article
-
How to implement spin lock in go Language Interview?
This article mainly introduces the example analysis of how to achieve spin lock that is often asked in go language interviews. Friends in need can use it for reference. I hope it can be helpful2023-11-11 -
Common grammar sugar sharing in Golang
Syntactic sugars, also known as sugar grammars, were developed by British computer scientist Peter Landin to denote a certain type of syntax in a programming language that does not affect functionality but is easy to use. Here's a look at some of the commonly used syntactic sugars in Golang2023-05-05 -
A detailed explanation of the use of cel in golang
CEL is a non-Turing complete expression language, designed to be fast, portable and safe to execute,CEL can be used alone, can also be embedded in other products, this article will give you an introduction to golang how to use cel, need friends can refer to2023-11-11 -
Details How to use the validator for parameter verification in go-zero
This article mainly introduces how to use the validator library to do parameter verification some very practical use skills, including translation verification error message, user-defined prompt message field name, custom verification method, etc., interested can understand the following2024-01-01 -
Golang pipe interacts remotely in different scenarios
This article mainly introduces the remote interaction of Golang pipe in different scenarios. pipe implements redirection from one process to another process. It is a two-way data channel for inter-communication2023-03-03 -
Go Build Complete steps to compile the package file
go build command is used to compile Go language program and generate executable file, it can compile Go source code into machine code, and package it into executable file, convenient to run on different operating systems, this article mainly introduces you about Go Build compile package file complete steps, need friends can refer to the next2024-02-02 -
Implementation of Go coroutine timeout control
This article mainly introduces the implementation of Go coroutine timeout control, the article through the example code is introduced in detail, has a certain reference value, interested partners can refer to it2021-08-08 -
Do you really understand generics in Golang
The introduction of generics in Golang after the 1.18 version update was an important update that brought much more flexibility and reusability to Golang. Today, we will delve into the concept of generics, why generics are needed, the syntax of generics, and how to use it in practice2023-05-05 -
This article explains the principle of Go Http Server
This article mainly introduces the Go Http Server principle example detailed explanation, need friends can use for reference, hope to be helpful, I wish you a lot of progress, early promotion and pay rise2023-01-01 -
golang sync.Cond synchronization mechanism application and implementation
In Go, there is a channel specifically created for synchronous communication, so you rarely see the use of sync.Cond, but it is also a means of concurrency control, today we will understand its related implementation, deepen the use of synchronization mechanism2023-09-09
Latest comments