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.

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序