C++ PIMP Scenario: GUI Framework
Button.h (Public Interface):
// Button.h
#include <string>
class Button {
public:
Button(const std::string& label);
~Button();
void setLabel(const std::string& label);
std::string getLabel() const;
void setBackgroundColor(const std::string& color);
std::string getBackgroundColor() const;
void setSize(int width, int height);
std::pair<int, int> getSize() const;
void onClick();
private:
class ButtonImpl; // Forward declaration
ButtonImpl* pimpl; // Pointer to the implementation
};
Button.cpp (Implementation):
// Button.cpp
#include "Button.h"
// Private Implementation Class
class Button::ButtonImpl {
public:
std::string label;
std::string backgroundColor;
int width;
int height;
// ... other implementation details
};
// Public Interface Implementation
Button::Button(const std::string& label)
: pimpl(new ButtonImpl{label, "DefaultColor", 100, 30}) {}
Button::~Button() {
delete pimpl;
}
void Button::setLabel(const std::string& label) {
pimpl->label = label;
// ... other implementation details
}
std::string Button::getLabel() const {
return pimpl->label;
}
void Button::setBackgroundColor(const std::string& color) {
pimpl->backgroundColor = color;
// ... other implementation details
}
std::string Button::getBackgroundColor() const {
return pimpl->backgroundColor;
}
void Button::setSize(int width, int height) {
pimpl->width = width;
pimpl->height = height;
// ... other implementation details
}
std::pair<int, int> Button::getSize() const {
return {pimpl->width, pimpl->height};
}
void Button::onClick() {
// Handle click event
// ... other implementation details
}
In this extended example:
- The `Button` class now has methods to get and set the background color and size of the button.
- The `ButtonImpl` class contains additional data members for the background color, width, and height.
- Users of the `Button` class can interact with these properties through the public methods without knowing the details of the implementation.
This kind of separation is particularly valuable in large projects where implementation details can change frequently, and you want to shield users from those changes.
No comments:
Post a Comment