我有两个类,它们都遵循相同的接口(interface)(IAccount)。它们每个都有一个名为 Preferences 的属性,该属性遵循另一个接口(interface) (IAccountPreference)。
我想要一种通用创建首选项属性的方法(即采用 IAccount 并为其创建首选项的方法,而不关心传入的 IAccount 的实际类型)。实现这一目标的最佳方法是什么?
我能想到的最佳解决方案是实用工厂方法,如下所示(半伪代码):
private IAccountPreference getAccountPreference(IAccount acc){
switch(acc.GetType()){
case AccountType1:
return new PreferenceForAccountType1();
case AccountType2:
return new PreferenceForAccountType2();
.
.
.
}
}
并使用它来获取对正确的具体类型的引用。虽然看起来很乱。
我是否缺少更明显的解决方案?
最佳答案
在这种情况下,我通常使用的模式是为 IAccount 提供一个名为“CreateDefaultPreferences”的函数,该函数创建并返回该帐户的正确子类型的 IAccountPreference 实例。
关于c# - 一般创建正确具体类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236501/