views:

88

answers:

1

I have a UserControl that has a BaseClass object as a public member. Right now I'm doing the following to discern between which type of object I need to instantiate:

Public WithEvents theForm As OrderForm

Protected Sub Page_Load(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Load

    Select Case Form
        Case OrderItem.ItemsFor.Invoice
            theForm = New Invoice(FormID)
        Case OrderItem.ItemsFor.PurchaseOrder
            theForm = New PurchaseOrder(FormID)
    End Select

End Sub

Where both Invoice and PurchaseOrder inherit OrderForm as their base class and FormID is an integer. I know this is wrong, but I would like to know the correct way to do this.

+1  A: 

Normally I would remove the logic from the code behind and create a simple abstract factory. The purpose of an abstract factory is to create objects of the same base type but can discern which type to create from a discriminator. A simple example in C# is described below:

public class OrderFormFactory
{
   public static IOrderForm Create(string orderType, int formId)
   {
       IOrderType orderTypeToCreate = null;
       switch(orderType)
       {
          case OrderType.Invoice:
              orderTypeToCreate = new Invoice(formId);
              break;
          case OrderType.PurchaseOrder:
              orderTypeToCreate = new PurchaseOrder(formId);
              break;
          default:
              throw new ArgumentException("Order Type of " + orderType + " is not supported";
       }
       return orderTypeToCreate;
   }
}
Michael Mann
i don't have an interface IOrderForm... if I returned the BaseClass, would it still work?
Jason
Yes, it will still work, I was just using the interface as an example.
Michael Mann