mirror of
https://github.com/iandinwoodie/cpp-design-patterns-for-humans.git
synced 2025-12-16 20:17:08 +03:00
Added bridge example.
This commit is contained in:
114
README.md
114
README.md
@@ -930,7 +930,118 @@ vary independently."
|
||||
|
||||
#### Programmatic Example
|
||||
|
||||
TODO
|
||||
Translating our WebPage example from above. Here we have the web page hierarchy.
|
||||
|
||||
```cpp
|
||||
class WebPage
|
||||
{
|
||||
public:
|
||||
virtual std::string getContent(void) = 0;
|
||||
};
|
||||
|
||||
class About : public WebPage
|
||||
{
|
||||
public:
|
||||
About(Theme::ptr_t theme)
|
||||
: theme_(theme)
|
||||
{
|
||||
}
|
||||
|
||||
std::string getContent(void)
|
||||
{
|
||||
return "About page in " + theme_->getColor();
|
||||
}
|
||||
|
||||
private:
|
||||
Theme::ptr_t theme_;
|
||||
};
|
||||
|
||||
class Projects : public WebPage
|
||||
{
|
||||
public:
|
||||
Projects(Theme::ptr_t theme)
|
||||
: theme_(theme)
|
||||
{
|
||||
}
|
||||
|
||||
std::string getContent(void)
|
||||
{
|
||||
return "Projects page in " + theme_->getColor();
|
||||
}
|
||||
|
||||
private:
|
||||
Theme::ptr_t theme_;
|
||||
};
|
||||
|
||||
|
||||
class Careers : public WebPage
|
||||
{
|
||||
public:
|
||||
Careers(Theme::ptr_t theme)
|
||||
: theme_(theme)
|
||||
{
|
||||
}
|
||||
|
||||
std::string getContent(void)
|
||||
{
|
||||
return "Careers page in " + theme_->getColor();
|
||||
}
|
||||
|
||||
private:
|
||||
Theme::ptr_t theme_;
|
||||
};
|
||||
```
|
||||
|
||||
And the separate theme hierarchy.
|
||||
|
||||
```cpp
|
||||
class Theme
|
||||
{
|
||||
public:
|
||||
typedef std::shared_ptr<Theme> ptr_t;
|
||||
virtual std::string getColor(void) = 0;
|
||||
};
|
||||
|
||||
class DarkTheme : public Theme
|
||||
{
|
||||
public:
|
||||
std::string getColor(void)
|
||||
{
|
||||
return "dark palette";
|
||||
}
|
||||
};
|
||||
|
||||
class LightTheme : public Theme
|
||||
{
|
||||
public:
|
||||
std::string getColor(void)
|
||||
{
|
||||
return "light palette";
|
||||
}
|
||||
};
|
||||
|
||||
class AquaTheme : public Theme
|
||||
{
|
||||
public:
|
||||
std::string getColor(void)
|
||||
{
|
||||
return "aqua palette";
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Here is how this can be used:
|
||||
|
||||
```cpp
|
||||
Theme::ptr_t darkTheme = std::make_shared<DarkTheme>();
|
||||
About about(darkTheme);
|
||||
Careers careers(darkTheme);
|
||||
|
||||
// Output: About page in dark palette
|
||||
std::cout << about.getContent() << std::endl;
|
||||
// Output: Careers page in dark palette
|
||||
std::cout << careers.getContent() << std::endl;
|
||||
```
|
||||
|
||||
#### When To Use
|
||||
|
||||
@@ -962,7 +1073,6 @@ objects and compositions uniformly.
|
||||
|
||||
#### Programmatic Example
|
||||
|
||||
TODO
|
||||
|
||||
#### When To Use
|
||||
|
||||
|
||||
Reference in New Issue
Block a user