Design Pattern Download: The Proxy Pattern
The Proxy pattern is a Structural Pattern used in software engineering when we want to do some sort of processing before accessing the actual service, this could be logging, verifying a user, checking a cache, etc…
Example
We are trying to create and use a service object, however creating that object is very expensive and it does not make sense to create the service object if the user is not verified and therefore there is no reason to create the expensive service object. To get around this, we create a proxy class with the same methods as the real service but it does some pre-processing or checks before creating and then calling the actual service. We would use this if we do not own the real service and therefore cannot add these checks to that class.
When to use the Proxy?
- When you want to lazily create the real service only when it is absolutely necessary.
- When you want to do some pre-process step before calling the service like cache management, logging or access validation.
What is the Proxy Pattern composed of?
- The Real Service( the class we want to put a proxy in front of (we may not own this class))
- The Proxy Service(the class that sits in front of the real service and calls it after validating the request)
Implementation
The Real Service
The Proxy Service
The ProxyService has a list of the allowed users, so before we even create a RealService object we want to verify that the user is indeed allowed to access the service. Below is an example of a client using this proxy and the result…
Access Denied!
Creating Real Service
User Kim is using the Real Service
User Jack is using the Real Service