proxy - Harsh4999/Design-Patterns GitHub Wiki
Proxy
Use
- Proxy acts on behalf of the object and is used for lots of reasons some of the main reasons are protections proxy, remote proxy and virtual proxy.
- When we want an object which can work in place of an object
- Client is unaware of existence of proxy
- Lazy loading uses proxy
Uml
- Subject interface = Used by client has some operation
- Real subject = Implementation of subject interface with method definition
- Proxy = Implements subject and maintains a reference of actual object for providing actual functionality.
Implementation
- Proxy must implement same interface as real subject
- We can either create actual object later when required or ask for one in constructor
- In method implementations of proxy we implement the functionality before delegating to real object
- To provide client with instance of a proxy we can provide them factory
- There a 2 types of proxies 1) Static 2) Dynamic
- When we want to absolutely hold on to the object till we need it hence saving memory and processor this is useful
- Dynamic proxy allows us to create proxies at runtime
- Dynamic proxy will help in changing classes for proxy in runtime
- How the proxy gets hold of real object depends on use case we must ensure to not initialize object unless and until its absolutely necessary
- Proxy can cache some state till object is not made
- When using proxy we must check for sync
- Eg: Hibernate uses proxy for lazy loading while virtual loading