Purpose
Provide a surrogate or placeholder for another object to control access to it.
Use an extra level of indirection to support distributed, controlled, or intelligent access.
Add a wrapper and delegation to protect the real component from undue complexity.
Play with an Example
Hope we all are using bank account. Via different mediums we can able to credit/debit money from a bank account.
On this example lets discuss about bank account debit cases. It is able to debit the account money via the debit cards and check book. We can say like the debit cards and check books are the proxy for your account. Means if we do some operations with debit cards or check books. It actually reflecting on the corresponding bank account. Lets create the same example by programming
There is an Account interface which having all the methods allowed for the bank. This is a common interface for all proxies and non proxy classes
BankAccountImpl is the non proxy class. The functions inside BankAccountImpl not calling directly, it is calling via proxies.
CheckBookProxy is a proxy for BankAccountImpl
CreditCardProxy is a proxy for BankAccountImpl
In the main we are accessing the BankAccountImpl amount via CheckBookProxy and CreditCardProxy classes
Points to Remember
- Identify the leverage or "aspect" that is best implemented as a wrapper or surrogate.
- Define an interface that will make the proxy and the original component interchangeable.
- Consider defining a Factory that can encapsulate the decision of whether a proxy or original object is desirable.
- The wrapper class holds a pointer to the real class and implements the interface.
- The pointer may be initialized at construction, or on first use.
- Each wrapper method contributes its leverage, and delegates to the wrappee object.
Advanced Points
- Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
- Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests.
No comments:
Post a Comment