在Factory中使用Delegate Dictionary Pattern和参数

时间:2016-06-23 18:37:35

标签: c#

我目前有一个工厂类,如下所示:

public static class OrderFactory
{
    public static Order GetOrder(OrderInformation orderInfo, Logger logger, string overlayPath)
    {
        switch (orderInfo.Type)
        {
            case OrderType.Print:
                return new Print(orderInfo, logger, overlayPath);
            case OrderType.Cad:
                return new Cad(orderInfo, logger, overlayPath);
            case OrderType.Litho:
                return new Litho(orderInfo, logger, overlayPath);
            case OrderType.Error:
            default:
                return new OrderError(orderInfo, logger, overlayPath);
        }
    }
}

public abstract class Order
    {
        protected OrderInformation OrderInfo { get; set; }
        protected Logger Logger { get; set; }
        protected string OverlayPath { get; set; }
        public Order(OrderInformation orderInfo, Logger logger, string overlayPath)
        {
            OrderInfo = orderInfo;
            Logger = logger;
            OverlayPath = overlayPath;
        }
        public abstract Task<bool> CreateImage()
    }

public class Print : Order
    {
        public Print(OrderInformation orderInfo, Logger logger, string overlayPath)
            : base(orderInfo, logger, overlayPath)
        { }

        public override async Task<bool> CreateThumbs(CorelAppWrapper corelAppWrapper, int timeBeforeFirstAbort, int timeBeforeRetryAbort)
        {

我想主要使用委托模式或其他东西来避免使用switch语句,并且知道有一天我们必须快速扩展此方法。我想使用委托字典模式或类似的东西。我尝试过这样的代码:

    private delegate Order Order(OrderInformation orderInfo, Logger logger, string overlayPath);

    private static readonly Dictionary<OrderType, Order>
           mTypeConstructors = new Dictionary<OrderType, Order>
           {
               { OrderType.Print, (orderInfo, logger, overlayPath) => new Print(orderInfo, logger, overlayPath) },
               ...//etc
           };

这样做会引发错误,指出Print类型无法转换为Order类型。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

我已经通过代码中的一些更改来实现它。为简单起见,我已从构造函数移动了对象的创建(more detail

  public static Order GetOrder(OrderInformation orderInfo, Logger logger, string overlayPath)
    {
        return mTypeConstructors[orderInfo.Type](orderInfo, logger, overlayPath);           
    }


  private static readonly Dictionary<OrderType, Func<OrderInformation, Logger, string, Order>>
  mTypeConstructors = new Dictionary<OrderType, Func<OrderInformation, Logger, string, Order>>
               {
                 { OrderType.Print, Print.Create },
                ///...

               };


   public class Print : Order
    {
        ...

        public static Print Create(OrderInformation orderInfo, Logger logger, string overlayPath)
        {
           ...
        }