Use an example of giving gifts to a girl to tell the proxy model.
Girls tend to be shy, so the way to chase girls is to give gifts to girls through the indirect way of girlfriends. The maiden honey is to represent the pursuer to send the gift, the maiden honey only needs to quote the pursuer, gives the person who pursues the gift and the discourse can.
Directly on the program, relatively simple:
#include <iostream> #include <string>using namespace Std;class girl{public:void setName (string name) {this- >name = name;} String GetName () {return name;} private:string name;}; Class givegift{public:virtual void giveflowers () = 0;}; Class Pursuit:public Givegift{public:pursuit (Girl *girl) {this->girl = Girl;} void Giveflowers () {cout << girl->getname () << "---you is so beautiful like flowers, I love u!" << Endl;} Private:girl *girl;};/ /bff--best friend Foreverclass proxybff:public givegift{public:proxybff (Girl *girl) {this->pursuit = new Pursuit ( Girl);} void Giveflowers () {pursuit->giveflowers ();} void Showmyself () {cout << "I'm girlfriends, my name is:" << name << Endl;} void SetName (string name) {this->name = name;} Private:pursuit *pursuit;string name;}; int main () {Girl *girl = new Girl (); Girl->setname ("Wu Chaomei"); PROXYBFF *proxy = new PROXYBFF (girl);p roxy->setname ("Yu Ying");p roxy->showmyself ();p roxy->giveflowers (); return 0;}
Operation Result:
[Email protected]:~/code/designpattern/proxypattern$./a.out I am a friend, my name is: Yu Ying Wu Chaomei---you is so beautiful like flowers, I lo ve u!
---------------------------------------------------------------------------------------------
Analysis:
By adding a middle tier, the agent embodies the idea of an object-oriented single function.
Forward proxy and Reverse proxy:
The above gift is actually a positive proxy for an example, that is, the agent is the client, just like the agent used in the browser to fill a proxy server, and then the Internet is forwarded through the proxy server.
And the reverse proxy, is and the server is in one, the agent is the server side, the client does not know the existence of the reverse proxy server, the client request, the first to reach the proxy server, the proxy server according to the request to go back to the backend server to obtain data returned to the client, you can put different services on different servers, Thus achieving load balancing. Nginx can do the forward proxy can also do reverse proxy server.
To implement a smart pointer using the proxy mode:
Proxy mode of design mode