哪个阶级结构更可取? [英] Which class structure is more desirable?

查看:131
本文介绍了哪个阶级结构更可取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道其中的两个模式是最好的。目前我使用选项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是更好的选择的普遍共识。貌似我有很多重构提前:•

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的保存方法将使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆