I have 2 strategies. According to the data from the request, I want to call the strategy I want and perform operations in a single line. How can I achieve this? So far my code is like this
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
}
MY service:
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
}
Years ago I made an operation using make[] . I was able to create the relevant strategy and perform the operations by matching it with an enum according to a parameter in the request. I can't remember it right now, I couldn't find any examples on the internet. Can you help me?
Aucun commentaire:
Enregistrer un commentaire