2009-09-04 61 views
1

我有一个UserControl,它具有一个BaseClass对象作为公共成员。现在,我做以下我需要实例化的对象类型之间进行辨别:构造函数多态帮助

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 

如果双方InvoicePurchaseOrder继承OrderForm作为其基类和FormID是一个整数。我知道这是错误的,但我想知道正确的方法来做到这一点。

回答

2

通常我会从后面的代码中移除逻辑并创建一个简单的抽象工厂。抽象工厂的目的是创建具有相同基本类型的对象,但可以辨别从鉴别器创建的类型。在C#中的一个简单的例子如下:

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

我没有接口IOrderForm ...如果我返回的BaseClass,它仍然工作? – Jason

+0

是的,它仍然可以工作,我只是使用界面作为例子。 –