赞
踩
获取一个csgo饰品的定价,需要从多个渠道(steam、buff、igxe……)等等。
需求很简单,下班前搞定吧。
1、先定义一个传输对象:dto.go
- package price
-
- type GetPriceReq struct {
- GoodsId int64 `json:"goods_id"`
- }
2、具体实现:interface.go
- package price
-
- import (
- "context"
- "strings"
- )
-
- // GoodsStrategyPrice 饰品定价策略
- type GoodsStrategyPrice interface {
- // GetPrice 根据饰品ID获取系统自定义价格
- GetPrice(ctx context.Context, req *GetPriceReq) int64
- }
-
- // GoodsStrategy 用于选择和执行策略
- type GoodsStrategy struct {
- strategy GoodsStrategyPrice
- }
-
- // SetStrategy 选择策略
- func (s *GoodsStrategy) SetStrategy(strategy GoodsStrategyPrice) {
- s.strategy = strategy
- }
-
- // GetPrice 执行策略
- func (s *GoodsStrategy) GetPrice(ctx context.Context, req *GetPriceReq) int64 {
- return s.strategy.GetPrice(ctx, req)
- }
-
- // GetPriceByGoods 根据策略获取价格
- func GetPriceByGoods(ctx context.Context, req *GetPriceReq, strategy string) int64 {
- // 策略
- var strategyObj GoodsStrategyPrice
-
- // 去除空格、转小写
- strategy = strings.ToLower(strings.TrimSpace(strategy))
-
- switch strategy {
- case "steam":
- strategyObj = NewGoodsSteamPrice()
- case "buff":
- strategyObj = NewGoodsBuffPrice()
- case "igxe":
- strategyObj = NewGoodsIgxePrice()
- default: // 默认策略
- strategyObj = NewGoodsSteamPrice()
- }
-
- obj := &GoodsStrategy{}
- obj.SetStrategy(strategyObj)
-
- return obj.GetPrice(ctx, req)
- }
-
- // GoodsSteamPrice Steam定价
- type GoodsSteamPrice struct{}
-
- // NewGoodsSteamPrice 定价策略:Steam定价
- func NewGoodsSteamPrice() *GoodsSteamPrice {
- return &GoodsSteamPrice{}
- }
-
- // GetPrice 根据饰品ID获取系统自定义价格:Steam定价
- func (p *GoodsSteamPrice) GetPrice(ctx context.Context, req *GetPriceReq) int64 {
- return 100
- }
-
- // GoodsBuffPrice Buff定价
- type GoodsBuffPrice struct{}
-
- // NewGoodsBuffPrice 定价策略: Buff定价
- func NewGoodsBuffPrice() *GoodsBuffPrice {
- return &GoodsBuffPrice{}
- }
-
- // GetPrice 根据饰品ID获取系统自定义价格:Buff定价
- func (p *GoodsBuffPrice) GetPrice(ctx context.Context, req *GetPriceReq) int64 {
- return 200
- }
-
- // GoodsIgxePrice Igxe定价
- type GoodsIgxePrice struct{}
-
- // NewGoodsIgxePrice 定价策略: Igxe定价
- func NewGoodsIgxePrice() *GoodsIgxePrice {
- return &GoodsIgxePrice{}
- }
-
- // GetPrice 根据饰品ID获取系统自定义价格:Igxe定价
- func (p *GoodsIgxePrice) GetPrice(ctx context.Context, req *GetPriceReq) int64 {
- return 300
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
是骡子是马,拉出来溜溜
- package main
-
- import (
- "fmt"
- "strategy/price"
- )
-
- func main() {
-
- strategy := "steam"
-
- priceData := price.GetPriceByGoods(nil, &price.GetPriceReq{GoodsId: 1}, strategy)
-
- fmt.Printf("策略:%s 定价:%d\n", strategy, priceData)
- }
输出结果:
一气呵成,还真能运行起来,这你受得了嘛
这段代码展示了策略模式(Strategy Pattern)的设计思想。策略模式是一种行为设计模式,它使你能在运行时改变对象的行为。
以下是策略模式的关键组件在代码中的体现:
通过这种方式,该设计允许程序在运行时选择不同的算法或策略来处理同一类型的问题,而无需知道具体策略是如何实现的,提高了代码的灵活性和可扩展性。如果未来需要添加新的定价策略,只需实现GoodsStrategyPrice接口并相应地修改策略选择逻辑即可。
我为人人,人人为我,美美与共,天下大同。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。