vendredi 30 juillet 2021

Creating a single factory for unrelated objects

I have several classes that are not related to each other.

public class Apple
{
    
}

public class Giraffe
{
    
}

I can create a separate factory for each but I want to get a structure like below.

Factory<Apple>.CreateSingle();

I want to produce a single apple with the code above. Also with the following code;

Factory<Giraffe>.CreateCollection(20);

I want to get 20 giraffes.

To do this, I created an IFactory generic interface.

public interface IFactory<out T>
{
    T CreateSingle();
    IEnumerable<T> CreateCollection(int count);
}

And a factory for each type;

public class AppleFactory : IFactory<Apple>
{
    public Apple CreateSingle() =>
        new()
        {
           //some code
        };

    public IEnumerable<Apple> CreateCollection(int count)
    {
          // CreateSingle X count times, add to collection and return
    }
}

public class GiraffeFactory: IFactory<Giraffe>
{
    public Giraffe CreateSingle() =>
        new()
        {
           //some code
        };

    public IEnumerable<Giraffe> CreateCollection(int count)
    {
          // CreateSingle X count times, add to collection and return
    }
}

The main factory looks like this;

public static class Factory<T>
{
    private static IFactory<T> GetFactory()
    {
        if (typeof(T) == typeof(Apple)) return (IFactory<T>) new AppleFactory();
        if (typeof(T) == typeof(Giraffe)) return (IFactory<T>) new GiraffeFactory();
        return null;
    }
    public static T CreateSingle() => GetFactory().CreateSingle();
    public static IEnumerable<T> CreateCollection(int count) => GetFactory().CreateCollection(count);


}

The if structure here looks pretty ugly. Is there a way I can do what I want to do in a cleaner way? These days, I am trying to learn design patterns and I force myself to use design patterns. The code may seem unnecessarily cluttered for this reason. It's totally experimental.

Aucun commentaire:

Enregistrer un commentaire