Factory design pattern using enumerations and inheritance

I have a conceptual problem. I would like to use the factory design template, using an enumeration, to find out what type of object to create. But when it comes to inheritance in another assembly, I stick to my listing ...

Let me explain the case:

I am creating a Framework for several projects that manage the fruits.

I am creating an interface IFruitimplemented by an abstract class Fruitfrom which it inherits Strawberry, Appleand Pear.

I create an enum FruitTypesthat contains Strawberry, Appleand Pear.

I create FruitFactoryusing a virtual method: GiveMeANewFruit(FruitTypes newFruit)which returns IFruit.

Everything is fine.

I send my framework around the world, and someone in our Spanish plant also needs to manage bananas.

It will create a class Bananathat inherits Fruit.

It will create SpanishFruitFactoryone that inherits from FruitFactoryand overrides the virtual method GiveMeANewFruit, here is the code that may be in this method:

Public Override IFruit GiveMeANewFruit(FruitTypes newFruit)
{
    if (newFruit == FruitTypes.Banana)
        return new Banana();
    else
        return base.GiveMeANewFruit(newFruit);
}

But hey, here's the problem. I know that languages โ€‹โ€‹like C # do not allow enums to be inherited. So my boyfriend cannot add value Bananato the enumeration FruitTypes.

So, what would be the best template to replace an enumeration so that I can provide the outside world with the opportunity to add new types of objects to my concept?

Knowing that I do NOT want to have anything outside the source code (without an XML file, no database, or anything else that provides a list of types).

Do you have any tips?

+4
2

, - static class. , php. static class enum, string, .

0

factory, int, , : -

public class FruitTypes
{
    public const int Strawberry = 1;
    public const int Apple = 2;
    public const int Pear = 3;
}

public class SpanishFruitTypes : FruitTypes
{
    public const int Banana = 4;
}

: -

factory.GiveMeANewFruit(FruitTypes.Pear)

factory.GiveMeANewFruit(SpanishFruitTypes.Banana)
0

Source: https://habr.com/ru/post/1533763/


All Articles