【问题标题】:How do I refactor two classes with similar functionality?如何重构具有相似功能的两个类?
【发布时间】:2016-06-22 11:56:27
【问题描述】:

我的类具有相同名称的方法,它们做同样的事情,但它们的实现方式不同。

例如:

class converterA {
    map(Item1 item1) {
        // Implementation details.
    }

    convert(Item1 item1) {
        // Implementation details.
    }

    translate(Item1 item1) {
        // Implementation details.
    }
}

class converterB {
    map(Item2 item2) {
    // Implementation details.
    }

    convert(Item2 item2) {
    // Implementation details.
    }

    translate(Item2 item2) {
    // Implementation details.
    }
}

我考虑过使用接口,但问题是方法采用不同的参数。然而,模板也不完全适合,因为 Item1 和 Item2 以不同的方式运行。换句话说,它们没有通用方法,因此模板也不完全适合。

这里有重构代码的解决方案吗?

【问题讨论】:

  • 在这种情况下你想通过重构获得什么?
  • 我只是想知道是否有办法压缩代码或有一个可以扩展的接口样式类,因为这两个类具有相似的功能。

标签: c++11 design-patterns


【解决方案1】:

鉴于您的评论“如何...拥有可以扩展的界面样式类”,您可能有兴趣使用模板来表达常见的“界面”:

template <typename Item>
struct Converter
{
    virtual void map(Item) = 0;
    virtual void convert(Item) = 0;
    virtual void translate(Item) = 0;
};

class converterA : public Converter<Item1> {
    void map(Item1 item1) final { ... }
    void convert(Item1 item) final { ... }
    void translate(Item1 item) final { ... }
};
class converterB : public Converter<Item2> {
    ...same kind of thing...
};

它给你的只是他们共享的“转换器”接口的一个表达式,一些函数签名和名称匹配的编译时强制执行(例如,如果你更改Converter&lt;&gt;,你会被提醒更新所有派生类型),以及使用指向它们派生的模板实例的指针/引用来处理派生类的能力(这对您来说没有任何表面用途)。

【讨论】:

    【解决方案2】:

    我在考虑使用模板专业化,但如果它们都使用完全不同的方法,那并不值得,尽管它会更具可读性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多