Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 402
jmrah Avatar asked May 08 '26 04:05

jmrah


1 Answers

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();
    }
}
like image 152
Pienterekaak Avatar answered May 09 '26 23:05

Pienterekaak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!