【问题标题】:Best Approach to refactor common code in several classes?在几个类中重构公共代码的最佳方法?
【发布时间】:2014-08-22 00:39:02
【问题描述】:

我正在尝试清理一些代码,并且我看到有三个类,所以除了这三个之外,所有类都具有相同的属性,其中一些具有比其他更多的属性,并且需要比其他两个保存更多或更少的属性。

我有类似的东西

//class 1
public class GenerateQKey
{
      public void DoSomething()
      {
          //this one uses a specific class with some parameters
          var KeySet = new GenerateQSetOfK()
              {
                   KeyName = "some key";
                   KeyChain = "Some key chain";
                   KeyManufacturer = "Manufacturer";
              }

           someCall.Save(KeySet);
      }
}

然后我还有一个:

//class 2
public class GenerateDifferentKey
{
      public void DoSomething()
      {
          //this one uses a specific class with some parameters + more
          var KeySet = new GenerateDifferenKey()
              {
                   Name = "some key";
                   Chain = "Some key chain";
                   Manufacturer= "Manufacturer";
                   Price = 3.00m;
              }

           someOtherCall.Save(KeySet);
      }
}

还有另一个相同的原理.. 他们都在做基本相同的事情,只是使用不同的 API 并保存到不同的地方。我想以一种非常好的方式重构它,但我不确定它会是什么。

也许有一个管理器类,它接收 GenerateQKey 或 GenerateDifferentKey 并在确定键的类型时调用特定的 api,但是参数呢?我应该创建一个基类吗?

我正在努力成为一名更好的开发人员,您的意见将真正有助于实现这一目标。

【问题讨论】:

  • 您可以使用Inheritance 来清理它,但请注意,这可能会变得混乱。看看Composition over Inheritance
  • I see there are three classes that so the very same thing except for all three some have more properties than others and need to save more or less properties than the other two. 抱歉什么?
  • 我认为OP意味着有3个类具有相同的目的,但是A类的属性为foo,B类的属性为foobar,以及类C 具有属性foobarbaz。另一种选择是使用超类并仅分配您需要的值。读取属性时要非常小心,如果它们没有分配给你,你会得到一个对象引用错误。

标签: c# asp.net


【解决方案1】:

对我来说,这听起来像是Template method pattern 可以解决的问题。

您的模板方法将在所有子类之间具有相似的步骤,并且“使用不同 API”和“保存到不同位置”的方法将是每个子类将以不同方式实现的抽象方法。

public abstract class SharedClass
{
   abstract CallApi();
   abstract Save();

   public void MyTemplateMethod()
   {
     // shared steps...

     // Call abstract templated method
     this.CallApi();

     // more shared steps...

     // Call abstract templated method
     this.Save(); 
   }
}

public class ChildClass1 : SharedClass
{
  public void CallApi()
  {
     // I use API #1
  }

  public void Save()
  {
    // I save by doing it way #1
  }
}

public class ChildClass2 : SharedClass
{
  public void CallApi()
  {
     // I use API #2
  }

  public void Save()
  {
    // I save by doing it way #2
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多