3

静的 C++ ライブラリの一部のクラスでは、ライブラリのユーザーとライブラリ自体に異なるインターフェイスを提供したいと考えています。

例:

class Algorithm {

  public:

    // method for the user of the library
    void compute(const Data& data, Result& result) const;


    // method that I use only from other classes of the library
    // that I would like to hide from the external interface
    void setSecretParam(double aParam);

  private:

    double m_Param;
}

私の最初の試みは、外部インターフェイスを ABC として作成することでした。

class Algorithm {

  public:

    // factory method that creates instances of AlgorithmPrivate
    static Algorithm* create();

    virtual void compute(const Data& data, Result& result) const = 0;
}

class AlgorithmPrivate : public Algorithm {

  public:

    void compute(const Data& data, Result& result) const;

    void setSecretParam(double aParam);

  private:

    double m_Param;
}

長所:

  • アルゴリズムのユーザーは内部インターフェースを見ることができません

短所:

  • ユーザーはファクトリ メソッドを使用してインスタンスを作成する必要があります
  • ライブラリ内からシークレット パラメーターにアクセスする場合は、Algorithm を AlgorithmPrivate にダウンキャストする必要があります。

私が達成しようとしていることを理解していただければ幸いです。何か提案があればお待ちしております。

4

2 に答える 2

3

最も簡単な方法はsetSecretParam() private、次のものを作成して作成することfriendですAlgorithm

void setSecretParam(Algorithm& algorithm, double aParam)
{
  void setSecretParam(double aParam);
}
于 2010-02-25T09:25:15.833 に答える
1

継承を置き換える「通常の容疑者」はBridge パターンです。抽象クラス AlgorithmImp から派生した「Imp」の階層を定義し、ライブラリ ヘッダーで適切なアルゴリズムのみを公開できます。次に、アルゴリズムのインスタンスを次のように作成できます。

ConcreteAlgorithm ca1(SomeParam, new LibraryUserAlgorithm());
ConcreteAlgorithm ca2(SomeParam, new InternalAlgorithm());
于 2010-02-25T08:49:42.427 に答える