dsimib1625 2014-06-10 03:57
浏览 38
已采纳

工厂模式的替代方案,可能有数百个小类

I'm working on a small game/simulator, written in GoLang, in which there will be potentially hundreds of abilities. For each player, they will have between 1 and 3 abilities. I'll have these stored with either strings or Ids. What is the best way to instantiate these abilities. Normally I'd use a factory class, but with as many as I'm talking about, I'm not sure that's the best way.

  • 写回答

1条回答 默认 最新

  • dqyuipw44576 2014-06-10 11:36
    关注

    You can still use the factory pattern, it's what the encoding/gob package uses.

    playground: http://play.golang.org/p/LjR4PTTCvw

    For example in abilities.go you could have

    type Ability interface {
        Execute()
    }
    
    var abilities = struct {
        m map[string]AbilityCtor
        sync.RWMutex
    }{m: make(map[string]AbilityCtor)}
    
    type AbilityCtor func() Ability
    
    func Register(id string, newfunc AbilityCtor) {
        abilities.Lock()
        abilities.m[id] = newfunc
        abilities.Unlock()
    }
    
    func GetAbility(id string) (a Ability) {
        abilities.RLock()
        ctor, ok := abilities.m[id]
        abilities.RUnlock()
        if ok {
            a = ctor()
        }
        return
    }
    

    Then for each ability (in separate files probably) you could do something like :

    type Fireball struct{}
    
    func (s *Fireball) Execute() {
        fmt.Println("FIREBALL EXECUTED")
    }
    
    func init() {
        Register("Fireball", func() Ability {
            return &Fireball{}
        })
    }
    
    func main() {
        if fireball := GetAbility("Fireball"); fireball != nil { //could be nil if not found
            fireball.Execute()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行