重新设计附加代码段的建议

时间:2013-01-21 10:36:56

标签: c++ polymorphism

我的程序需要像这样运行:

./myprogram inputType [Can be I1, I2 or I3]

该计划的大部分功能如下:

void Foo::foo (IType inputType) {
    // Some common code
    if (inputType == I1) ... // some I1 specific code
    if (inputType == I2) ... // Some I2 specific code
    ...// similarly for I3
}

对inputType的这些检查分散在多个地方,随着时间的推移变得越来越难以管理。我曾想过将这些代码重构为:

InputType* iType = new InputTypeI1(); // or I2 or I3

void Foo::foo (IType inputType) {
    // Some common code
    iType.DoSomething(this, arg1, arg2,..)
}

class InputType1 : public InputType 
{
     // Virtual functions.. (with default implementations)
}

InputType1::DoSomething(Foo* f, Arg1* arg1, Arg2* arg2)
{
    f->DoSomethingFor1(arg1, arg2);
}

这导致为I1,I2或I3组织事物以及根据输入类型自动调用相关函数。 但是,我觉得这可以做得更好。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

很难从你提供的代码片段中看出来,但我考虑使用三个派生的foo类,FooI1,FooI2和FooI3,并使用基于InputType的工厂构建适当的foo类。

然后,所有专业化都会在每个新类的虚拟方法中实现。

class FooI1: public Foo {
 void doSomething() {...};
}

同样适用于I2 / I3 ..

Foo * fooFactory(InputType iType) 
{ 
   return new FooX - depending on iType
};
Foo *f = fooFactory(i)

f->doSomething();

答案 1 :(得分:1)

您当前的代码与Foo和InputType结合:

  1. Foo creates InputType Object
  2. InputType calls Foo function

建议的解决方案是:

 1. Decouple InputType and Foo by using composites mode
    Foo could hold a pointer to `InputType*` then call InputType `virtual` function.    
 2. To make InputType, a factory will simple enough. 

示例代码:

class InputType
{
 public:
    virtual ~InputType();
    virtual void DoSomething();
};

InputType* MakeInputObject(const IType& inputType)
{
   return new InputTypeX; 
}

class Foo
{
public:
  Foo(const InputType& input) : input_type_ptr(MakeINputObject(input) {} 
  void DoSomething() { input_type_ptr->DoSomeThing(); }

private:
  std::unique_ptr<InputType> input_type_ptr;
};