jeudi 16 mai 2019

Factory Pattern and Dependency Injection

In my C#, MVVM application, I took over code that is generating a class object. Given the requirement that I was handed, I might need to create multiple objects based on a value. So I decided to refactor class generation by using the factory pattern and that worked for that requirement. As I proceeded in the task more requirement have come up, which includes creating an object not only by the original string variable but also by a boolean variable. In addition, to those variables, a parameter needs to be passed into the object, which I think I should do by dependency injection. My question is should I be using the Factory pattern at this point or something else. How do I incorporate the boolean variable and the parameter in whatever recommended design pattern. The code example of what I am using is below.

 public abstract class PivotRequestFactory
 {
    public abstract PivotRequest GetPivotRequest();
 }

public class ConcretePivotRequestFactory : PivotRequestFactory
{

    public ConcretePivotRequestFactory()
    {

    }
    public override PivotRequest GetPivotRequest()
    {
        try
        {

            return new PivotRequest();
        }
        catch (Exception ex)
        {

            throw;
        }
    }
}

private PivotRequest GetPivotRequest(string DataSetName)
    {
        PivotRequestFactory factory = null;
        try
        {
            switch (DataSetName)
            {
                case DatasetNames.Default:
                    if (IsTrue) { factory = new ConcretePivotRequestFactory(); }
                    else { factory = new ConcretePivotRequestFactory2); }
                    break;
                case DatasetNames.SoSo:
                    if (IsTrue) { factory = new ConcretePivotRequestFactory3(); }
                    else { factory = new ConcretePivotRequestFactory4(); }
                    break;
                default:
                    break;
            }
        }
        catch (Exception)
        {

            throw;
        }
        return factory.GetPivotRequest();
    }

Aucun commentaire:

Enregistrer un commentaire