How to avoid switch-case in a factory method of child classes

前端 未结 1 1723
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 07:07

Lets say we have a family of classes (cards, for the sake of it), and we need to instantiate them based on some identifier. A factory method would look like this:

         


        
相关标签:
1条回答
  • 2020-12-13 07:38

    Instead of storing the type in the dictionary, you could store a Func<Card>:

    private Dictionary<int, Func<Card>> cardFactories = 
    {
        { 13, () => new King() },
        // etc
    }
    
    public Card GetCard(int cardNumber) 
    {        
        var factory = cardFactories[cardNumber];
        return factory();
    }
    

    In the case of cards, I'd probably make them immutable to start with and just populate the dictionary with the cards themselves, but that's a different matter :)

    0 讨论(0)
提交回复
热议问题