哪种类结构更可取? [英] Which class structure is more desirable?
问题描述
我不确定这两种模式"中哪一种最好.目前我使用选项 A(与提供者结合实现持久性),但我现在偏向于 B,尤其是考虑到单元测试能够使用依赖注入"模型.
I'm not sure which of these two "patterns" is the best. Currently I use option A (in conjunction with a provider for implementing persistence), but I'm now erring towards B, especially in light of unit tests being able to use the "dependency injection" model.
选项 A:
class ClassA
{
ClassA() { }
Save();
static List<ClassA> GetClassAs();
}
选项 B:
class ClassA
{
ClassA() { }
Save();
}
class ClassARepository
{
ClassARepository() { }
List<ClassA> GetClassAs();
}
我想我要问的是,类公开返回其自身实例集合的静态方法是一种好的做法吗?
I think what I'm asking is, is it good practice for a class to expose static methods that return collections of instances of itself?
似乎普遍认为选项 B 是更好的选择.看起来我前面有很多重构:S
There seems to be a general consensus that Option B is the better choice. Looks like I have plenty of refactoring ahead :S
推荐答案
选项 B 看起来有点像 ActiveRecord 模式(我假设 ClassA 中的 Save 方法将使用 ClassARepository ?),这在某些情况下很好,但是,如果您有相当复杂的域模型,我不会使用ActiveREcord"模式.
Option B looks a bit like the ActiveRecord pattern (I Assume the Save method in ClassA will use the ClassARepository ? ), which is good in some situations, but, if you have rather complex domain-model, I wouldn't use the 'ActiveREcord' pattern.
相反,我会使用这样的模型:
Instead, I would use such a model:
public class ClassA
{
public int Id {get; private set;}
public string Name {get; set;}
}
public class ClassARepository
{
public ClassA Get( int id );
public void Save( ClassA item );
}
这意味着所有与持久化相关的逻辑都放在 ClassARepository 类中,而 ClassA 也没有直接访问存储库的权限.
Which means that all persistence related logic is put in the ClassARepository class, and ClassA has also no direct access to the repository.
这篇关于哪种类结构更可取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!