ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 概述 先通过抽象方式实现步骤,在通过具体类替换抽象接口 ## 示例 ### 一次性密码功能 让我们来考虑一个一次性密码功能(OTP)的例子。将 OTP 传递给用户的方式多种多样(短信、邮件等)。但无论是短信还是邮件,整个 OTP 流程都是相同的: 1. 生成随机的 n 位数字。 2. 在缓存中保存这组数字以便进行后续验证。 3. 准备内容。 4. 发送通知。 5. 发布。 <details> <summary>main.go</summary> ``` package main import "fmt" // 模板方法 type iOtp interface { genRandomOTP(int) string saveOTPCache(string) getMessage(string) string sendNotification(string) error publishMetric() } // 方式一:在调用时候选择 // type otp struct { // } // func (o *otp) genAndSendOTP(iOtp iOtp, otpLength int) error { // otp := iOtp.genRandomOTP(otpLength) // iOtp.saveOTPCache(otp) // message := iOtp.getMessage(otp) // err := iOtp.sendNotification(message) // if err != nil { // return err // } // iOtp.publishMetric() // return nil // } // 方式二 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) err := o.iOtp.sendNotification(message) if err != nil { return err } o.iOtp.publishMetric() return nil } // 具体实施 type sms struct { otp } func (s *sms) genRandomOTP(len int) string { randomOTP := "1234" fmt.Printf("SMS: generating random otp %s\n", randomOTP) return randomOTP } 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) publishMetric() { fmt.Printf("SMS: publishing metrics\n") } // 具体实施 type email struct { otp } func (s *email) genRandomOTP(len int) string { randomOTP := "1234" fmt.Printf("EMAIL: generating random otp %s\n", randomOTP) return randomOTP } 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) publishMetric() { fmt.Printf("EMAIL: publishing metrics\n") } func main() { // 方式一 // otp := otp{} // smsOTP := &sms{ // otp: otp, // } // smsOTP.genAndSendOTP(smsOTP, 4) // emailOTP := &email{ // otp: otp, // } // emailOTP.genAndSendOTP(emailOTP, 4) // fmt.Scanln() // 方式一 smsOTP := &sms{} o := otp{ iOtp: smsOTP, } o.genAndSendOTP(4) fmt.Println("") emailOTP := &email{} o = otp{ iOtp: emailOTP, } o.genAndSendOTP(4) } ``` </details> <br /> 输出 ``` MS: generating random otp 1234 SMS: saving otp: 1234 to cache SMS: sending sms: SMS OTP for login is 1234 SMS: publishing metrics EMAIL: generating random otp 1234 EMAIL: saving otp: 1234 to cache EMAIL: sending email: EMAIL OTP for login is 1234 EMAIL: publishing metrics ```