如何使用不同的版本参数重构相同的类

时间:2012-12-19 04:26:09

标签: java refactoring

像下面的两个类一样,除了调用不同版本的params之外,它们几乎看起来相同,那么如何重构它们呢?

import com.v1.B;
import com.v1.C;
class A1
{
  public A1(B,C)
  public dosomething1()
  {
    //do something with B and C
  }
  public dosomething2()
  {
    //do something
  }
}

A2类:

import com.v2.B;
import com.v2.C;
class A2
{
  public A2(B,C)
  public dosomething1()
  {
    //do something with B and C
  }
  public dosomething2()
  {
    //do something
  }
}

1 个答案:

答案 0 :(得分:1)

您应首先为这两种类型创建基类或接口,例如com.v.BaseBcom.v1.B com.v2.B以促进多态性,然后您可以使用单个泛型类而不会出现任何重复:

import com.v.B;
import com.v.C;
class A
{
  public A(B,C)
  public dosomething1()
  {
    //do something with B and C
  }
  public dosomething2()
  {
    //do something
  }
}