加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 工厂是否应该有一个带参数的构造函数?

发布时间:2020-12-15 05:40:15 所属栏目:百科 来源:网络整理
导读:假设我想构建一个字符串列表(这不是真实的情况,但听起来更简单). 我的字符串工厂列表的界面看起来像这样 public interface IStringsListFactory{ Liststring Create();} 但是,让我说我的一个具体工厂需要从文件/数据库等获取这个字符串列表. public class St
假设我想构建一个字符串列表(这不是真实的情况,但听起来更简单).

我的字符串工厂列表的界面看起来像这样

public interface IStringsListFactory{
   List<string> Create();
}

但是,让我说我的一个具体工厂需要从文件/数据库等获取这个字符串列表.

public class StringsListFromFile : IStringsListFactory{

   private StreamReader _streamReader;
   public StringsListFromFile(StreamReader sr) //StreamReader is just an example.
   {
       _streamReader = sr;
   }

   public List<string> Create(){ 
     ///recover the strings using my stream reader... 
   }
}

我知道这种方法可行,但我想知道它是否会破坏工厂模式以将参数传递给工厂的构造函数,所以我不会破坏我的界面.这样做有没有对应的?还有其他解决方案我没有想到吗?我问了太多问题!?! (是的,我知道这个的答案!)

解决方法

构造函数中的参数和构造函数本身应该只执行一个且只能执行一个作业:即注册依赖项.有时,需要将依赖性“注入”工厂,如Mark Seeman在 this answer年的抽象工厂模式所述.
public class ProfileRepositoryFactory : IProfileRepositoryFactory
{
    private readonly IProfileRepository aRepository;
    private readonly IProfileRepository bRepository;

    public ProfileRepositoryFactory(IProfileRepository aRepository,IProfileRepository bRepository)
    {
        if(aRepository == null)
        {
            throw new ArgumentNullException("aRepository");
        }
        if(bRepository == null)
        {
            throw new ArgumentNullException("bRepository");
        }

        this.aRepository = aRepository;
        this.bRepository = bRepository;
    }

    public IProfileRepository Create(string profileType)
    {
        if(profileType == "A")
        {
            return this.aRepository;
        }
        if(profileType == "B")
        {
            return this.bRepository;
        }

        // and so on...
    }
}

在这种情况下它是有效的,但不是在你的情况下,因为:

>它使你的工厂有状态
>如果参数(流)作为方法参数注入,它会使您的工厂更加灵活

public class StringsListFromFile : IStringsListFactory{

   public List<string> Create(StreamReader sr){ 
     ///recover the strings using my stream reader... 
   }
}

>如果您的界面应该灵活输入,请使用泛型>另外,最好返回IEnumerable< string>而不是List< string>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读