Added proxy example.

This commit is contained in:
Ian Dinwoodie
2019-04-29 20:29:05 -04:00
parent cc3778702b
commit a4fb260005

View File

@@ -1619,7 +1619,78 @@ operations on the real object are invoked.
#### Programmatic Example #### Programmatic Example
TODO Taking our security door example from above. Firstly we have the door class
and an implementation of door
```cpp
class Door
{
public:
typedef std::shared_ptr<Door> ptr_t;
virtual void open(void) = 0;
virtual void close(void) = 0;
};
class LabDoor : public Door
{
public:
void open(void)
{
std::cout << "Opening lab door" << std::endl;
}
void close(void)
{
std::cout << "Closing lab door" << std::endl;
}
};
```
Then we have a proxy to secure any doors that we want
```cpp
class SecuredDoor
{
public:
SecuredDoor(Door::ptr_t door)
: door_(door)
{
}
void open(const std::string& password)
{
if (authenticate(password)) {
door_->open();
} else {
std::cout << "No way, Jose!" << std::endl;
}
}
void close(void)
{
door_->close();
}
private:
bool authenticate(const std::string& password)
{
return password == "Bond007";
}
Door::ptr_t door_;
};
```
Here is how this can be used:
```cpp
Door::ptr_t labDoor = std::make_shared<LabDoor>();
SecuredDoor securedDoor(labDoor);
securedDoor.open("invalid"); // Output: No way, Jose!
securedDoor.open("Bond007"); // Output: Opening lab door
securedDoor.close(); // Output: Closing lab door
```
#### When To Use #### When To Use