Proxy Pattern comes under Structural Pattern.
According to Gang Of Four Intent of Proxy Pattern is to Provide a surrogate or placeholder for another object to control access to it.
UML DIAGRAM:
SAMPLE CODE:
#include <iostream>
using namespace std;
class Vote {
public:
virtual void castVote(string name, int age) = 0;
};
class VoteSystem : public Vote {
public:
void castVote(string name, int age)
{
cout << "NAME : " << name << ", AGE : " << age << " Casted Vote Successfully" << endl;
}
};
class IndianVoteSystem : public Vote { // Proxy class
Vote* voteOper;
public:
IndianVoteSystem()
{
voteOper = new VoteSystem();
}
void castVote(string name, int age)
{
if (age >= 18) { // if age is more than 18 cast vote
voteOper->castVote(name, age);
}
else {
cout << age << " Years is Not Eligible Age to Cast Vote in India" << endl;
}
}
};
int main()
{
string name;
int age;
Vote* indiaPoll = new IndianVoteSystem();
cout << "Name ? "; cin >> name;
cout << "Age ? "; cin >> age;
indiaPoll->castVote(name, age);
return 0;
}
OUTPUT:
Name ? hirthik
Age ? 16
16 Years is Not Eligible Age to Cast Vote in India
According to Gang Of Four Intent of Proxy Pattern is to Provide a surrogate or placeholder for another object to control access to it.
UML DIAGRAM:
SAMPLE CODE:
#include <iostream>
using namespace std;
class Vote {
public:
virtual void castVote(string name, int age) = 0;
};
class VoteSystem : public Vote {
public:
void castVote(string name, int age)
{
cout << "NAME : " << name << ", AGE : " << age << " Casted Vote Successfully" << endl;
}
};
class IndianVoteSystem : public Vote { // Proxy class
Vote* voteOper;
public:
IndianVoteSystem()
{
voteOper = new VoteSystem();
}
void castVote(string name, int age)
{
if (age >= 18) { // if age is more than 18 cast vote
voteOper->castVote(name, age);
}
else {
cout << age << " Years is Not Eligible Age to Cast Vote in India" << endl;
}
}
};
int main()
{
string name;
int age;
Vote* indiaPoll = new IndianVoteSystem();
cout << "Name ? "; cin >> name;
cout << "Age ? "; cin >> age;
indiaPoll->castVote(name, age);
return 0;
}
OUTPUT:
Name ? hirthik
Age ? 16
16 Years is Not Eligible Age to Cast Vote in India
Name ? sharma
Age ? 34
NAME : sharma, AGE : 34 Casted Vote Successfully
Name ? rahul
Age ? 18
NAME : rahul, AGE : 18 Casted Vote Successfully