php小编柚子为您介绍如何根据传入类型调用策略模式。策略模式是一种面向对象的设计模式,它允许根据不同的情况选择不同的算法或策略。在实际开发中,我们经常需要根据不同的类型来执行不同的操作。通过使用策略模式,我们可以将这些不同的操作封装成不同的策略类,并根据传入的类型来调用相应的策略,从而实现灵活的逻辑控制。接下来,我们将详细介绍如何在PHP中使用策略模式来根据传入类型调用相应的策略。
我有两个策略。根据请求的数据,我想调用我想要的策略并在一行中执行操作。我怎样才能实现这个目标?到目前为止我的代码是这样的
package strategy type strategy interface { distribute(request model.routerequest) (*model.distributeresponse, error) getstrategytype() int }
package strategy type strategy interface { distribute(request model.routerequest) (*model.distributeresponse, error) getstrategytype() int }
package strategies import ( "github.com/x/internal/enum" "github.com/x/internal/model" "github.com/x/internal/repository" ) type distributebranchstrategy struct { repo repository.repository } func newdistributebranchstrategy(repo repository.repository) *distributebranchstrategy { return &distributebranchstrategy{ repo: repo, } } func (d *distributebranchstrategy) distribute(request model.routerequest) (*model.distributeresponse, error) { return nil, nil } func (d *distributebranchstrategy) getstrategytype() int { return enum.branch }
package strategies import ( "github.com/x/internal/enum" "github.com/x/internal/model" "github.com/x/internal/repository" ) type distributetransfercenterstrategy struct { repo repository.repository } func newdistributetransfercenterstrategy(repo repository.repository) *distributetransfercenterstrategy { return &distributetransfercenterstrategy{ repo: repo, } } func (d *distributetransfercenterstrategy) distribute(request model.routerequest) (*model.distributeresponse, error) { return nil, nil } func (d *distributetransfercenterstrategy) getstrategytype() int { return enum.transfer_center }
我的服务:
package service import ( "github.com/x/internal/model" "github.com/x/internal/repository" "github.com/x/internal/strategy/strategies" ) type DistributeService struct { repo repository.Repository distributeBranchStrategy strategies.DistributeBranchStrategy } type Distribute interface { Distribute(vehicleNumberPlate string, request model.DistributeRequest) *model.DistributeResponse } func NewDistributeService(repo repository.Repository, strategy strategies.DistributeBranchStrategy) *DistributeService { return &DistributeService{ repo: repo, distributeBranchStrategy: strategy, } } func (d *DistributeService) Distribute(vehicleNumberPlate string, request model.DistributeRequest) *model.DistributeResponse { // TODO: Implement this method for _, x := range request.RouteRequest { d.distributeBranchStrategy.Distribute(x) } return nil }
几年前,我使用 make[] 进行了一次操作。我能够创建相关策略并根据请求中的参数将其与枚举相匹配来执行操作。我现在不记得了,我在互联网上找不到任何例子。你能帮我吗?
您可以将所有可用策略放入地图中:
var strategies = map[int]func(repository.repository) strategy { enum.branch: func(repo repository.repository) strategy { return newdistributebranchstrategy(repo) }, ... }
然后调用:
s, ok: = strategies[x] if !ok { // error } s(repo).Distribute(...)
以上是如何根据传入类型调用策略模式的详细内容。更多信息请关注PHP中文网其他相关文章!