From a4fb260005927d0ec961900ae69a8c9d6737874f Mon Sep 17 00:00:00 2001 From: Ian Dinwoodie Date: Mon, 29 Apr 2019 20:29:05 -0400 Subject: [PATCH] Added proxy example. --- README.md | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 87adca1..f77ab49 100644 --- a/README.md +++ b/README.md @@ -1619,7 +1619,78 @@ operations on the real object are invoked. #### 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 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(); +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