如何在不使用IF条件的情况下执行此操作

use*_*358 2 c# oop object-oriented-analysis

我有一个定义一个方法的接口.此接口具有多个以不同方式实现该接口的类.

例如:

interface IJob {
  void DoSomething();
}

class SomeJob : IJob{
  public void DoSomething() {
    // Do something ...
  }
}

class AnotherJob : IJob {
  public void DoSomething() {
    // Do something ...
  }
}

...
Run Code Online (Sandbox Code Playgroud)

我的工厂类将有一堆这些IF语句

if (some condition)
{
   IJob job = new SomeJob (); 
else
{
   IJob job = new AnotherJob (); 
}
Run Code Online (Sandbox Code Playgroud)

有没有办法避免每次出现新情况时修改工厂类.这可以通过添加一个实现IJob的新类来完成吗?

编辑: [我想弄清楚Antiifcampaign的这些人正在尝试做什么]

谢谢你的时间...

Ant*_*kov 5

你必须以某种方式连接条件和决定.

Dictionary<int, Action<IJob>> _methods = new ...
Run Code Online (Sandbox Code Playgroud)

填写字典:

_methods.Add(0, () => {return new SomeJob();});
_methods.Add(1, () => {return new AnotherJob();});
Run Code Online (Sandbox Code Playgroud)

然后使用它:

public IJob FactoryMethod(int condition)
{
   if(_methods.ContainsKey(condition))
   {
      return _methods[int]();
   }
   return DefaultJob; //or null
}
Run Code Online (Sandbox Code Playgroud)

您需要在应用程序启动时填写字典.从配置文件或其他一些代码.因此,当您遇到新情况时,您无需更换工厂.你喜欢这个变种吗?

  • 我建议使用不同类型的int(也许是枚举?)来使意图更具可读性和显而易见性(1表示这里`var job = JobFactory.GetJob(1)`?)`var job = JobFactory.GetJob( Requirement.CleanUp)`传达意图更好 (3认同)