lundi 25 septembre 2017

Generic Factory Pattern

Trying to convert a multiple DTO objects to the respective entities. Source is an excel document, each worksheet has unrelated to each other DTO objects. Let's assume that the first worksheet has name = "Products" and the related classes are:

class Product
{
    public int Id { get; set; }
    public string Description { get; set; }
}

class ProductDto
{
    public string Description { get; set; }
}

There are multiple sheets, each sheet has the DTO and I am trying to map it to the respective entity.

And the FactoryPattern will be:

public class FactoryPattern<K, T> where T : class, K, new()
{
    public static K CreateInstance()
    {
        K o;
        o = new T();
        return o;
    }
}

public class FactoryClass<T> where T : class
{
    public static IGenericReader<T> CreateInstance(string identifier)
    {
        switch (identifier)
        {
            case "Product":
                return (IGenericReader<T>) FactoryPattern<IGenericReader<Product>, ProductReader>.CreateInstance();
            //case "Business":
            //    return (IGenericReader<T>)FactoryPattern<IGenericReader<Business>, BusinessReader>.CreateInstance();
            default:
                throw new ArgumentException();
        }
    }
}

A reader implements this interface:

public interface IGenericReader<T>
{
    IEnumerable<T> Read(string item);
}

The implementation of the ProductReader is:

class ProductReader : IGenericReader<Product>
{
    public IEnumerable<Product> Read(string workSheetName)
    {
        return new List<Product>
        {
            new Product{Id = 5, Description = "ProductE"}
        };
    }

}

Currently my client code is like:

var reader = FactoryClass<Product>.CreateInstance("Product");
var values = reader.Read((List<ProductDto>)productDtos);

Could I abstract it somehow even more, in order for it to be like:

var reader = FactoryClass.CreateInstance(workSheet.Name);
var values = reader.Read(workSheet);

in order to have the code mentioned above in a tight loop that will iterate the worksheets of the excel document. I feel that having the worksheet name is enough identifier to instantiate the proper reader that gets the dto object or list of dto objects, and returns the entity object or list of entity objects.

Thanks

Aucun commentaire:

Enregistrer un commentaire