【问题标题】:What is best approach on designing this abstract class? (Part 1)设计这个抽象类的最佳方法是什么? (第1部分)
【发布时间】:2009-10-29 06:11:09
【问题描述】:

假设我有一个名为:租户和客户的抽象类。在这种情况下,租户就像多租户应用程序模型的应用程序所有者

这两个类之间的关系是多对一的关系。

public abstract class Tenant
{
  protected Int32 id;
  protected String name;

  public Int32 ID { get; set; }
  public String Name { get; set; }

  public abstract bool Add();
  public abstract bool Update();
  public abstract bool Delete(); 
}

public class ApplicationTenant: Tenant
{
  public ApplicationTenant() { }

  public override Int64 ID
  {
     get { return id; }
     set { id = value; }
  }

  public override String Name
  {
     get { return name; }
     set { name= value; }
  }

  ...

}

public abstract class Customer
{
  protected Int32 id;
  protected String name;
  protected Tenant tenant;

  public Int32 ID { get; set; }
  public String Name { get; set; }
  public Tenant Tenant { get; set; }

  public abstract bool Add();
  public abstract bool Update();
  public abstract bool Delete(); 
}

public class CorporateCustomer : Customer
{
  public CorporateCustomer () { }

  public override Int64 ID
  {
     get { return id; }
     set { id = value; }
  }

  public override String Name
  {
     get { return name; }
     set { name= value; }
  }

  public override Tenant Tenant
  {
     get { return tenant; }
     set { tenant= value; }
  }


  ...

}

这种设计的问题在于,当你这样做时:

CorporateCustomer customer = new CorporateCustomer();
customer.Tenant.ID = xx

在这种情况下,租户总是引用公共租户 Tenant { get;放; } 这实际上是我想要的是来自 ApplicationTenant 的那个,而不是一个抽象的。

如果它与其他对象相关,我应该删除此类 Customer 中的任何抽象吗?你的想法是什么?

【问题讨论】:

    标签: c#-2.0


    【解决方案1】:

    或者在您的 Customer 类中使用泛型。

    public abstract class Customer<TTenant> where TTenant: Tenant
    {
      protected Int32 id;
      protected String name;
      protected TTenant tenant;
    
      public Int32 ID { get; set; }
      public String Name { get; set; }
      public TTenant Tenant { get; set; }
    
      public abstract bool Add();
      public abstract bool Update();
      public abstract bool Delete(); 
    }
    

    【讨论】:

      【解决方案2】:

      您的意思是要访问具体实现 ApplicationTenant Properties 而不仅仅是获取租户抽象类?如果您确定租户是 ApplicationTenant 类型,则可以直接转换它,即

      ApplicationTenant appTenant = (ApplicationTenant)customer.Tenant;
      

      然后使用ApplicationTenant的功能。

      【讨论】:

      • 这个我懂。但是我在设计中的意思是,如果你强制 public Tenant Tenant { get;放; } 在客户抽象类中。这意味着 CorporateCustomer 类具有覆盖此租户属性的冗余(未使用),因为引用将指向 TEnant 类而不是 ApplicationTenant。希望这清楚。
      • 在没有测试您的代码的情况下,我注意到了一些事情。 a)您的覆盖是 Int64,而原始文件是 Int32。因此,我认为这不是实际的覆盖。覆盖必须具有完全相同的标头(返回类型 + 参数),不是吗? b)您的覆盖实际上什么也没做,那么为什么还要拥有它呢?需要一个更清晰的示例 c)即使您的覆盖被调用,它仍然保存回 Int32 使其冗余。需要一个更清晰的示例,其中覆盖实际上正在做某事。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多