前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >策略模式:使用上下文来传递参数

策略模式:使用上下文来传递参数

作者头像
运维开发王义杰
发布2023-08-16 19:46:09
2420
发布2023-08-16 19:46:09
举报

以下是一个使用上下文来传递参数的策略模式的例子,这个例子中,我们将创建两种不同的支付策略,它们需要不同的参数:

代码语言:javascript
复制
package main

import "fmt"


// Strategy Interface
type PaymentStrategy interface {
  Pay(ctx *PaymentContext) string
}


// Concrete Strategy
type PayPalStrategy struct{}


func (p *PayPalStrategy) Pay(ctx *PaymentContext) string {
  return fmt.Sprintf("Paid %d using PayPal. PayPal user: %s", ctx.Amount, ctx.PayPalUser)
}


// Concrete Strategy
type CreditCardStrategy struct{}


func (c *CreditCardStrategy) Pay(ctx *PaymentContext) string {
  return fmt.Sprintf("Paid %d using Credit Card. Card Number: %s", ctx.Amount, ctx.CreditCardNumber)
}


// Context
type ShoppingCart struct {
  ctx *PaymentContext
}


func (s *ShoppingCart) checkout() string {
  return s.ctx.Strategy.Pay(s.ctx)
}


// PaymentContext serves as the context for payment strategies
type PaymentContext struct {
  Strategy         PaymentStrategy
  Amount           int
  PayPalUser       string
  CreditCardNumber string
}


func main() {
  ctx := &PaymentContext{Strategy: &PayPalStrategy{}, Amount: 200, PayPalUser: "user@example.com"}
  cart := &ShoppingCart{ctx: ctx}
  fmt.Println(cart.checkout()) // Paid 200 using PayPal. PayPal user: user@example.com


  ctx = &PaymentContext{Strategy: &CreditCardStrategy{}, Amount: 300, CreditCardNumber: "1234-5678-9012-3456"}
  cart = &ShoppingCart{ctx: ctx}
  fmt.Println(cart.checkout()) // Paid 300 using Credit Card. Card Number: 1234-5678-9012-3456
}

在这个例子中,我们创建了一个新的 PaymentContext 结构,它既包含了支付策略,又包含了支付所需的所有参数。我们的 ShoppingCart 仍然只需要一个 PaymentContext 对象,但是现在 PaymentContext 可以包含任何支付策略需要的参数。

注意,这只是一种可能的解决方案,具体的解决方案取决于你的应用场景和需求。在一些情况下,可能需要采用其他的方法来处理不同策略需要不同参数的问题。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-05-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 运维开发王义杰 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档