Go design pattern template method pattern explanation and code sample _golang_script home

Go design pattern Template approach pattern explanation and code examples

Updated: August 24, 2023 08:21:09 Author: demo007x
Template method is a behavior design pattern, it defines an algorithm framework in the base class, allowing subclasses to rewrite the specific steps of the algorithm without modifying the structure, this article will give you a detailed introduction to the Go template method pattern through code examples, need friends can refer to the next

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 1234

Email: 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!

Related article

  • go语言面试如何实现自旋锁?

    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 helpful
    2023-11-11
  • Golang中常用的语法糖分享

    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 Golang
    2023-05-05
  • 在golang中使用cel的用法详解

    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 to
    2023-11-11
  • 详解go-zero如何使用validator进行参数校验

    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 following
    2024-01-01
  • Golang pipe在不同场景下远程交互

    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-communication
    2023-03-03
  • Go Build编译打包文件的完整步骤

    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 next
    2024-02-02
  • Go 协程超时控制的实现

    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 it
    2021-08-08
  • Golang中的泛型你真的了解吗

    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 practice
    2023-05-05
  • 一文详解Go Http Server原理

    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 rise
    2023-01-01
  • golang sync.Cond同步机制运用及实现

    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 mechanism
    2023-09-09

Latest comments