Creating internal and external interfaces to hide class / information

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

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 an external interface as 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:

  • Algorithm user cannot see the internal interface

Minuses:

  • The user must use the factory method to create instances.
  • I need to compress the algorithm into the Private algorithm when I want to access secret parameters from inside the library.

I hope you understand what I'm trying to achieve, and I look forward to any suggestions.

+3
source share
2 answers

- setSecretParam() private friend Algorithm:

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

" " " " . "Imps", AlgorithmImp, .

ConcreteAlgorithm ca1(SomeParam, new LibraryUserAlgorithm());
ConcreteAlgorithm ca2(SomeParam, new InternalAlgorithm());
+1

Source: https://habr.com/ru/post/1734379/


All Articles