douzhenggui8171 2017-03-29 01:57
浏览 104
已采纳

根据动态配置值实例化接口实现

New Gopher here, coming from Java land.

Let's say I have a some generic storage interface:

package repositories

type Repository interface {
  Get(key string) string
  Save(key string) string
}

I support multiple different backends (Redis, Boltdb, etc) by implementing this interface in separate packages. However, each implementation has unique configuration values that need to be passed in. So I define a constructor in each package, something like:

package redis 

type Config struct {
 ...
}

func New(config *Config) *RedisRepository {
  ...
}

and

package bolt

type Config struct {
  ...
}

func New(config *Config) *BoltRepository {
  ...
}

main.go reads a json configuration file that looks something like:

type AppConfig struct {
  DatabaseName string,
  BoltConfig *bolt.Config,
  RedisConfig *redis.Config,
}

Based on the value of DatabaseName, the app will instantiate the desired repository. What is the best way to do this? Where do I do it? Right now I'm doing some kind of horrible factoryfactory method which seems very much like a Go anti-pattern.

in my main.go, I have a function that reads the above reflected configuration values, selecting the proper configuration (either BoltConfig or RedisConfig) based on the value of DatabaseName:

func newRepo(c reflect.Value, repoName string) (repositories.Repository, error) {
    t := strings.Title(repoName)

    repoConfig := c.FieldByName(t).Interface()

    repoFactory, err := repositories.RepoFactory(t)
    if err != nil {
        return nil, err
    }

    return repoFactory(repoConfig)
}

and in my repositories package, I have a factory that looks for the repository type and returns a factory function that produces an instantiated repository:

func RepoFactory(provider string) (RepoProviderFunc, error) {
    r, ok := repositoryProviders[provider]
    if !ok {
        return nil, fmt.Errorf("repository does not exist for provider: %s", r)
    }
    return r, nil
}

type RepoProviderFunc func(config interface{}) (Repository, error)

var ErrBadConfigType = errors.New("wrong configuration type")

var repositoryProviders = map[string]RepoProviderFunc{
    redis: func(config interface{}) (Repository, error) {
        c, ok := config.(*redis.Config)
        if !ok {
            return nil, ErrBadConfigType
        }
        return redis.New(c)
    },
    bolt: func(config interface{}) (Repository, error) {
        c, ok := config.(*bolt.Config)
        if !ok {
            return nil, ErrBadConfigType
        }
        return bolt.New(c)
    },
}

bringing it all together, my main.go looks like:

cfg := &AppConfig{}
err = json.Unmarshal(data, cfg)
if err != nil {
    log.Fatalln(err)
}

c := reflect.ValueOf(*cfg)

repo, err := newRepo(c, cfg.DatabaseName)
if err != nil {
    log.Fatalln(err)
}

And yes, the second I was done typing this code I recoiled at the horror I had brought into this world. Can someone please help me escape this factory hell? What's a better way to do this type of thing -i.e selecting an interface implementation at runtime.

  • 写回答

1条回答 默认 最新

  • donglu3243 2017-03-29 14:17
    关注

    Do you need dynamic registration? It seems like the list of backends is already baked into your server because of the AppConfig type, so you may be better just writing the simplest possible factory code:

    func getRepo(cfg *AppConfig) (Repository, error) {
        switch cfg.DatabaseName {
        case "bolt":
            return bolt.New(cfg.BoltConfig), nil
        case "redis":
            return redis.New(cfg.RedisConfig), nil
        }
        return nil, fmt.Errorf("unknown database: %q", cfg.DatabaseName)
    }
    
    func main() {
        ...
        var cfg AppConfig
        if err := json.Unmarshal(data, &cfg); err != nil {
            log.Fatalf("failed to parse config: %s", err)
        }
        repo, err := getRepo(&cfg)
        if err != nil {
            log.Fatalln("repo construction failed: %s", err)
        }
       ...
    

    }

    Sure, you can replace this with generic reflection-based code. But while that saves a few lines of duplicated code and removes the need to update getRepo if you add a new backend, it introduces a whole mess of confusing abstraction, and you're going to have to edit code anyway if you introduce a new backend (for example, extending your AppConfig type), so saving a couple of lines in getRepo is hardly a saving.

    It might make sense to move getRepo and AppConfig into a repos package if this code is used by more than one program.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ue5运行的通道视频都会有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数