Last active
December 20, 2015 10:49
-
-
Save ErikZhou/6118935 to your computer and use it in GitHub Desktop.
Structural Patterns - Adapter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Structural Patterns - Adapter | |
| #include <iostream> | |
| using namespace std; | |
| typedef int Coordinate; | |
| typedef int Dimension; | |
| // Desired interface | |
| class Rectangle | |
| { | |
| public: | |
| virtual void draw() = 0; | |
| }; | |
| // Legacy component | |
| class LegacyRectangle | |
| { | |
| public: | |
| LegacyRectangle(Coordinate x1, Coordinate y1, Coordinate x2, Coordinate y2) | |
| { | |
| x1_ = x1; | |
| y1_ = y1; | |
| x2_ = x2; | |
| y2_ = y2; | |
| cout << "LegacyRectangle: create. (" << x1_ << "," << y1_ << ") => (" | |
| << x2_ << "," << y2_ << ")" << endl; | |
| } | |
| void oldDraw() | |
| { | |
| cout << "LegacyRectangle: oldDraw. (" << x1_ << "," << y1_ << | |
| ") => (" << x2_ << "," << y2_ << ")" << endl; | |
| } | |
| private: | |
| Coordinate x1_; | |
| Coordinate y1_; | |
| Coordinate x2_; | |
| Coordinate y2_; | |
| }; | |
| // Adapter wrapper | |
| class RectangleAdapter: public Rectangle, private LegacyRectangle | |
| { | |
| public: | |
| RectangleAdapter(Coordinate x, Coordinate y, Dimension w, Dimension h): | |
| LegacyRectangle(x, y, x + w, y + h) | |
| { | |
| cout << "RectangleAdapter: create. (" << x << "," << y <<"), width = " << w << ", height = " << h << endl; | |
| } | |
| virtual void draw() | |
| { | |
| cout << "RectangleAdapter: draw." << endl; | |
| oldDraw(); | |
| } | |
| }; | |
| int main() | |
| { | |
| Rectangle *r = new RectangleAdapter(120, 200, 60, 40); | |
| r->draw(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment