문제

For some classes of a static C++ library I want to offer different interfaces for the user of the library and for the library itself.

An example:

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;
}

My first attempt was to create the external interface as an 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;
}

Pros:

  • The user of Algorithm cannot see the internal interface

Cons:

  • The user has to use a factory method to create instances
  • I have to downcast Algorithm to AlgorithmPrivate when I want to access the secret parameters from inside the library.

I hope you understand what I try to achieve and I'm looking forward to any suggestions.

도움이 되었습니까?

해결책

The simplest way might be to make setSecretParam() private and make the following a friend of Algorithm:

void setSecretParam(Algorithm& algorithm, double aParam)
{
  void setSecretParam(double aParam);
}

다른 팁

The "usual suspect" to replace inheritance is Bridge pattern. You could define an hierarchy of "Imps" derived from abstract class AlgorithmImp and only expose appropriate algorithms in the library headers. Then an instance of algorithm can be created as

ConcreteAlgorithm ca1(SomeParam, new LibraryUserAlgorithm());
ConcreteAlgorithm ca2(SomeParam, new InternalAlgorithm());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top