2

私の質問の複雑なタイトルで申し訳ありません。概念的には非常に単純ですが、それを行うための適切な設計が見つかりません。

私はエンドユーザーがアクセスできる基本クラスを持っています:

class A {
private:
    // m is a functor
    Base* m;
};

class Base {
public:
    virtual void someInterface();
};

class DerivedT1 : public Base {
public:
    virtual void someInterface()
    {
        some_parameter++;
    }
private:
    int some_parameter; // how to set?
};

class DerivedT2 : public Base {
public:
    virtual void someInterface()
    {
        some_other_parameter += a_third_parameter;
    }
private:
    double some_other_parameter; // how to set?
    double a_third_parameter; // how to set?
};

some_parameterそして、の public インターフェイスsome_other_parameterから設定する最も一般的な方法を見つけようとしています。A

パラメータに数値を与えることを考えましたが、これは本当に見苦しく聞こえます。

これを行う美しいオブジェクト指向の方法はありますか?

4

3 に答える 3

0

これらの線に沿って何かをしたい場合

A a; a.setAlgorithmFamily(Algorithm::Type1);
a.getAlgorithmImplementation().setSomeParameter(34);

これは、それを行う方法の簡単で汚い例です。A::setAlgorithmType は基本的に、最も単純な形式のファクトリ パターンです。

nclude <iostream>
using namespace std;

class Algorithm {
public:
   virtual void setParameter(int value) = 0;
};
class AlgoX : public Algorithm {
   int mX;
public:
   void setParameter(int value) {
      cout <<"Setting X to " <<value <<endl;
      mX = value;
   }
};
class AlgoY : public Algorithm {
   int mY;
public:
   void setParameter(int value) {
      cout <<"Setting Y to " <<value <<endl;
      mY = value;
   }
};
class A {
public:
   void setAlgorithmType(std::string type) {
      cout <<"Now using algorithm " <<type <<endl;
      if(type == "X")
         mAlgorithm = new AlgoX();
      else if(type == "Y")
         mAlgorithm = new AlgoY();
   }
   Algorithm* getAlgorithmImplementation() { return mAlgorithm; }
private:
   Algorithm* mAlgorithm;
};

int main(int argc, char** argv) {
   A a;
   a.setAlgorithmType("X");
   a.getAlgorithmImplementation()->setParameter(5);
   return 0;
}

これは与える:

Now using algorithm X
Setting X to 5
于 2013-08-02T09:45:16.760 に答える