通常创建正确的混凝土类型的属性

时间:2014-12-01 20:15:57

标签: c# generics interface

我有两个类都遵循相同的接口(IAccount)。它们每个都有一个名为Preferences的属性,它附加到另一个接口(IAccountPreference)。

我想要一种通常创建首选项属性的方法(即获取IAccount并为其创建首选项的方法,而不关心传入的IAccount的实际类型)。实现这一目标的最佳方法是什么?

我能想到的最好的解决方案是实用工厂方法,如下所示(半pesudocode):

private IAccountPreference getAccountPreference(IAccount acc){
    switch(acc.GetType()){
          case AccountType1:
                return new PreferenceForAccountType1();
          case AccountType2:
                return new PreferenceForAccountType2();
          .
          .
          .
     }
}

并使用它来获得对正确具体类型的引用。虽然看起来很乱。

我错过了一个更明显的解决方案吗?

2 个答案:

答案 0 :(得分:3)

我通常在这种情况下使用的模式是给IAccount一个名为" CreateDefaultPreferences"为这种帐户创建并返回正确子类型的IAccountPreference实例。

答案 1 :(得分:2)

您可以将GetAccountPreference函数移动到IAccount接口中,这样IAccount的每个实现都将负责返回自己正确的IAccountPreference实现。

 public interface IAccount {
      ...// Other Contracts
      IAccountPreference GetAccountPreference();
 }

 public class AccountType1 : IAccount {
      ...// Properties, Methods, Constructor
      public IAccountPreference GetAccountPreference() {
           return new PreferenceForAccountType1();
      }
 }