2014-12-01 45 views
2

我有两个类都坚持相同的接口(IAccount)。它们每个都有一个名为Preferences的属性,它遵守另一个接口(IAccountPreference)。一般创建正确的混凝土类型属性

我想通常的方式来创建偏好属性(即一种方法,它需要一个IAccount并为它创建一个偏好,而不关心通过的IAccount的实际类型)。达到此目的的最佳方法是什么?

我能想出的最好的解决方案是一种实用工具工厂方法,像如下(半pesudocode):

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

并用它来获得正确的具体类型的引用。这看起来很乱。

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

+0

您可以更改具体类以实现具有所需属性的另一个接口吗? – Lee 2014-12-01 20:20:26

回答

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

美丽。我知道我错过了一些明显的答案。 – 2014-12-01 20:39:53

3

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

+0

示例代码将大大增加您的答案的价值 – 2014-12-01 20:28:32

+0

在这一点上,我会给出的任何示例都与@mreyeros已经给出的几乎相同。不是一个复制其他人的作品的人,我只是将每个人都引用到他的杰出范例中。 – 2014-12-01 20:37:32