The Pointer to Implementation (PIMPL) idiom shields implementation details and data from library users. When employing this idiom, it is common practice to define public methods in the PIMPL class rather than the public class. This poses the question: why not directly implement the methods in the public class?
Consider the following PIMPL implementation:
#include "cat.h" #include "cat_impl.h" Cat::Cat() { cat_ = new CatImpl; } Cat::~Cat() { delete cat_; } Cat::Purr(){ cat_->Purr(); }
In this example, the public class Cat acts as a "facade" for the PIMPL class CatImpl, which holds the actual implementation of the Purr() method. The PIMPL idiom offers several advantages:
Therefore, using the PIMPL idiom with public methods defined in the PIMPL class provides the benefits of decoupling, concealment, encapsulation, and code reuse, making it a valuable idiom for developing flexible and maintainable software libraries.
The above is the detailed content of Why Use the PIMPL Idiom with Public Methods in the Implementation Class?. For more information, please follow other related articles on the PHP Chinese website!