如何使用带有接口的工厂模式

时间:2012-03-20 23:47:14

标签: asp.net interface factory-pattern

我有以下界面:

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

以下实现接口的类:

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
   }
}

现在我正在尝试创建一个可以返回实现IPlateSubCategory接口的实例化对象的工厂。但是,我现在真的很挣扎,我无法正确使用代码。这是我到目前为止所做的,但我还没到那里。

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;
   }
}

任何帮助都将非常感谢。谢谢!

1 个答案:

答案 0 :(得分:1)

您已将IPlateSubCategory<T>定义为通用。您的工厂方法需要返回此接口的实现。如果您在* Item类上添加了后备接口,例如:

public class ThermoItem : IItem
{
}

然后您可以将工厂更改为:

    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");
        }
    }