Search code examples
asp.netinterfacefactory-pattern

How to use Factory pattern with an Interface


I have the following interface:

public interface IPlateSubCategory<T> {
   T GetItem(int plateID);
}

And the following classes that implements the interface:

public class Thermo : IPlateSubCategory<ThermoItem> {
   public ThermoItem GetItem(int plateID) {
      // code that implements GetItem
   }
}
public class Thickness : IPlateSubCategory<ThicknessItem> {
   public ThicknessItem GetItem(int plateID) {
      // code that implements GetItem
   }
}
public class Density : IPlateSubCategory<DensityItem> {
   public DensityItemGetItem(int plateID) {
      // code that implements GetItem
   }
}

And now I'm trying to create a factory that can return an instantiated object that implements the IPlateSubCategory interface. However, I'm really struggling at this point and I can't get the code right. Here is what I have so far, but I'm not quite there yet.

public class PlateSubCategory_Factory {
   public enum Categories {
      Thermo = 1,
      Thickness = 2,
      Density = 3
   }

   public static IPlateSubCategory GetPlateSubCategory(Categories cat) {
      IPlateSubCategory retObj = null;

      if (cat == Categories.Thermo)
         retObj = new Thermo();
      // other instantiations of classes that implement interface would follow

      return retObj;
   }
}

Any help would be great appreciated. Thanks!


Solution

  • You've defined IPlateSubCategory<T> to be generic. Your factory method needs to return an implementation of this interface. If you put a backing interface on your *Item classes e.g.:

    public class ThermoItem : IItem
    {
    }
    

    You can then change your factory to look like this:

        public static IPlateSubCategory<IItem> GetPlateSubCategory(Categories cat)
        {
            switch (cat)
            {
                case Categories.Thermo:
                    return new Thermo();
                case Categories.Thickness:
                    return new Thickness();
                case Categories.Density:
                    return new Density();
                default:
                    throw new ArgumentOutOfRangeException("cat");
            }
        }