The Proxy pattern is used to wrap a complex or resource intensive object inside a proxy class.
This pattern is practical if for example the creation of a specific object may lead to slow performance because it
takes a lot of memory.
In case you want to perform a simple quick action before the object is created to avoid performance loss
you can slot in a proxy object ahead of the actual creation of this performance critical object.
There are plenty of use cases for the proxy pattern. One of which is for example a login interface to a system which
only grants access to performance-heavy functionalities once a user has authorized.
This can protect social networking websites' servers like Facebook from high memory exhaustion. The heavy rich functionality
is only unlocked when a user has registered and really logged in.
Proxies are often used as frontends to classes which
Proxies as well as decorators pass requests on to other objects. What differentiates a proxy from a decorator is that the proxy is designed in advance before the code is written, whereas a decorator can be implemented in a later stage dynamically.
Imagine you design a simplified version of a check-in process for a flight like you might know it
in airports.
First you need to show a valid passport and a and valid ticket/boarding pass. If all your documents are
valid you are allowed to board the flight.
using System;
namespace Proxy
{
public class ProxyPattern
{
interface ICheckIn {
void AllowBoarding(string passengername);
}
public class Flight: ICheckIn {
public void AllowBoarding(string passengername) {
Console.WriteLine("Passenger " + passengername + " is allowed to board the flight");
}
}
public class Passenger {
public string name;
public bool hasValidPassport;
public bool hasValidBoardingPass;
public Passenger(string n, bool validpassport, bool validboardingpass) {
name = n;
hasValidPassport = validpassport;
hasValidBoardingPass = validboardingpass;
}
}
public class ProxyCheckIn: ICheckIn {
private Passenger passenger;
private Flight flight;
public ProxyCheckIn(Passenger p)
{
this.passenger = p;
this.flight = new Flight();
}
public void AllowBoarding(string passengername) {
if(passenger.hasValidPassport && passenger.hasValidBoardingPass) {
this.flight.AllowBoarding(passenger.name);
}
else{
Console.WriteLine("The passenger " + passenger.name + " is not allowed to board the flight.");
}
}
}
class MainClass
{
public static void Main()
{
Passenger passenger1 = new Passenger("John Doe", true, false);
ICheckIn checkin = new ProxyCheckIn(passenger1);
checkin.AllowBoarding(passenger1.name);
Passenger passenger2 = new Passenger("Judy Summers", true, true);
checkin = new ProxyCheckIn(passenger2);
checkin.AllowBoarding(passenger2.name);
}
}
}
}
The passenger John Doe is not allowed to board the flight. Passenger Judy Summers is allowed to board the flight.