The typical structure diagram for the agent mode is:
In fact, the idea of Agent mode is very simple.
Implementation of proxy mode:
Full code example: the implementation of proxy mode is very simple, here for the convenience of beginners to learn and reference, will give a complete implementation code (all code in C + + implementation, and under the VC 6.0 test run).
Code Snippets 1:proxy.h
Proxy.h
#ifndef _proxy_h_
#define _PROXY_H_
class subject{public
:
virtual ~subject ();
virtual void Request () = 0;
Protected:
Subject ();
Private:
};
Class Concretesubject:public subject{public
:
concretesubject ();
~concretesubject ();
void Request ();
Protected:
private:
};
Class proxy{public
:
Proxy ();
Proxy (subject* sub);
~proxy ();
void Request ();
Protected:
private:
subject* _sub;
#endif//~_proxy_h_
Code Snippets 2:proxy.cpp
Proxy.cpp
#include "Proxy.h"
#include <iostream>
using namespace std;
Subject::subject () {} subject::~subject () {}
concretesubject::concretesubject (
) {} Concretesubject::~concretesubject () {
}
void Concretesubject::request () {
cout<< " Concretesubject......request ...
"<<endl;
}
Proxy::P Roxy () {
}
Proxy::P Roxy (subject* sub) {
_sub = sub;
}
Proxy::~proxy () {
delete _sub;
}
void Proxy::request () {
cout<< "Proxy Request ..." <<endl;
_sub->request ();
}
Code Snippets 3:main.cpp
Main.cpp
#include "Proxy.h"
#include <iostream>
using namespace std;
int main (int argc,char* argv[]) {
subject* sub = new ConcreteSubject ();
proxy* p = new Proxy (sub);
P->request ();
return 0;
}
Code Description: The implementation of proxy mode is simple, there is no redundant explanation. As you can see, after the sample code runs, P's request requests are actually handed to the sub for actual execution.
Let's look at one more example:
#include <iostream> #include <string> using namespace std;
Class Receiver {private:string name;
Public:receiver (string name): Name (name) {} string GetName () {return name;
}
};
Class Subject {public:virtual void display () {}};
Class Sender:public Subject {Receiver *someone;
Public:void setreceiver (Receiver *someone) {this->someone = someone;
virtual void display () {cout<< "I hate you:" << someone->getname () <<endl;
}
};
Class Proxy:public Subject {public:subject *realobject;
void Setclient (Subject *client) {this->realobject = client;
} void Display () {realobject->display ();
}
};
int main () {Receiver *recv = new Receiver ("nobody");
Sender *obj = new Sender;
Obj->setreceiver (recv);
Proxy *proxy = new Proxy;
Proxy->setclient (obj);
Proxy->display ();
System ("pause"); ReTurn 0;
}
This shows that the most beneficial agent mode is the realization of a complete decoupling of logic and implementation.