The next
design pattern that is going to be covered in this blog series is Proxy
Design pattern.
As per the
name suggests, Proxy means a figure that can be used to represent the value of
something in calculation or ‘representing’ in the context of the design pattern
that we are discussing here. These are also named as surrogates, handles and
wrappers.
Real world example-
A credit card is a proxy for a bank account, which is a proxy for cash. No need
to carry loads of money with you all the time and the money directly being sent
shop’s bank account which results in win for both the parties. Instead of cash,
you are using different means like credit card to represent the real money. The
main purpose of proxy pattern is also the same – ‘To represent and control the access
to the object that is under their protection.’
When do we
use this designing pattern? – When you intend to cover the main object’s
complexity from the client.
Code to
display basic implementation of proxy design pattern.
#include <iostream>
using namespace std;
class ProxyBase {
public:
virtual void f() = 0;
virtual void g() = 0;
virtual void h() = 0;
virtual ~ProxyBase() {}
};
class Implementation : public ProxyBase {
public:
void f() { cout <<
"Implementation.f()" << endl; }
void g() { cout <<
"Implementation.g()" << endl; }
void h() { cout <<
"Implementation.h()" << endl; }
};
class Proxy : public ProxyBase {
ProxyBase* implementation;
public:
Proxy() { implementation = new Implementation();
}
~Proxy() { delete implementation; }
// Forward calls to the implementation:
void f() { implementation->f(); }
void g() { implementation->g(); }
void h() { implementation->h(); }
};
int main() {
Proxy p;
p.f();
p.g();
p.h();
}
Output:
References:
