Search code examples
enumsfactory-pattern

Factory Pattern: Enum Parameter vs Explicit Method Name?


Say you have a factory that returns instances of ILightBulb. Two ways (there may be more) of implementing the factory are as follows:

Option 1 - Passing in an enum type

enum LightBulbType
{
    Incandescent,
    Halogen,
    Led,
}

class ILightBulbFactory
{
    public ILightBulb Create(LightBulbType type)
    {
        switch (type)
        {
            case LightBulbType.Incandescent:
                return new IncandescentBulb();
            case LightBulbType.Halogen:
                return new HalogenBulb();
            case LightBulbType.Led:
                return new LedBulb();
        }
    }
}

Option 2 - Explicit method names

class ILightBulbFactory
{
    public ILightBulb CreateIncandescent()
    {
        return new IncandescentBulb();
    }

    public ILightBulb CreateHalogen()
    {
        return new HalogenBulb();
    }

    public ILightBulb CreateLed()
    {
        return new LedBulb();
    }
}

Which method is most preferable, and why?

Thanks.


Solution

  • In java, you can solve it in the enum, thus making sure that if you add new enums, all your code will remain working, instead of forgetting to add statements to your case.

    enum LightBulbType
    {
        Incandescent{
    
            @Override
            public ILightBulb getInstance() {
                return new IncandescentBulb();
            }
    
        },
        Halogen{
    
            @Override
            public ILightBulb getInstance() {
                return new HalogenBulb();
            }
    
        },
        Led{
    
            @Override
            public ILightBulb getInstance() {
                return new LedBulb();
            }
    
        };
    
        public abstract ILightBulb getInstance();
    }
    
    class ILightBulbFactory
    {
        public ILightBulb Create(LightBulbType type)
        {
           return type.getInstance();
        }
    }