mirror of
https://github.com/iandinwoodie/cpp-design-patterns-for-humans.git
synced 2025-12-17 04:24:40 +03:00
Added facade example.
This commit is contained in:
81
README.md
81
README.md
@@ -1380,7 +1380,86 @@ code, such as a class library.
|
|||||||
|
|
||||||
#### Programmatic Example
|
#### Programmatic Example
|
||||||
|
|
||||||
TODO
|
Taking our computer example from above. Here we have the computer class
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
class Computer
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
typedef std::shared_ptr<Computer> ptr_t;
|
||||||
|
|
||||||
|
void makeBootSound(void)
|
||||||
|
{
|
||||||
|
std::cout << "Beep!" << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void showLoadingScreen(void)
|
||||||
|
{
|
||||||
|
std::cout << "Loading..." << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void showWelcomeScreen(void)
|
||||||
|
{
|
||||||
|
std::cout << "Ready to use!" << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void closeEverything(void)
|
||||||
|
{
|
||||||
|
std::cout << "Closing all programs!" << std::endl;
|
||||||
|
}
|
||||||
|
void sleep(void)
|
||||||
|
{
|
||||||
|
std::cout << "Zzz" << std::endl;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Here we have the facade
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
class ComputerFacade
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
ComputerFacade(Computer::ptr_t computer)
|
||||||
|
: computer_(computer)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
void turnOn(void)
|
||||||
|
{
|
||||||
|
computer_->makeBootSound();
|
||||||
|
computer_->showLoadingScreen();
|
||||||
|
computer_->showWelcomeScreen();
|
||||||
|
}
|
||||||
|
|
||||||
|
void turnOff(void)
|
||||||
|
{
|
||||||
|
computer_->closeEverything();
|
||||||
|
computer_->sleep();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
Computer::ptr_t computer_;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Here is how this can be used:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
Computer::ptr_t computer = std::make_shared<Computer>();
|
||||||
|
ComputerFacade facade(computer);
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Beep!
|
||||||
|
// Loading...
|
||||||
|
// Ready to use!
|
||||||
|
facade.turnOn();
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// Closing all programs!
|
||||||
|
// Zzz
|
||||||
|
facade.turnOff();
|
||||||
|
```
|
||||||
|
|
||||||
#### When To Use
|
#### When To Use
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user