Proxy is a type of structural design pattern that let you come up with a replacement or substitute for another object. This method commands access to the original object and to which it lets you utilize a function before or after the request gets through to the original object. It has a similar interface as a service that makes interchangeable with a real object when passed to the client.
For example, The credit card is a proxy for any bank account, same as a bundle of cash. Both the credit card and the pile of money implement the same interface to which they are both used for making payment.
Structure of Proxy Method
The structure of the proxy method is into four connected parts:
- Service Interface
The implementation of the Proxy method uses the guidelines below:
- First, create a service interface to make proxy and service objects interchangeable if there is no preexisting one.
- Create the proxy class, and it should have a field for storing a reference to the interface.
- Implement the purpose of the proxy methods accordingly.
- Define a creation method that decides whether the user gets a proxy or a simple service.
- Implement lazy initialization for the object
The implementation code is in Python:
class Bank: """ Resource-intense object """ def debit(self): print("Money Debited Successfully \n") # The Credit Card is the bank proxy class BankProxy: def __init__(self): self.feeBalance = 10000 self.bank = None def debit(self): print("Proxy in action. Checking to see if the balance of student is clear or not...\n") if self.feeBalance >= 500: print("Withdrawal In Progress\n") # If the balance is less than 500, let him study. self.bank = Bank() self.bank.debit() else: # Otherwise, don't instantiate the college object. print("Insufficient Amount, Please try Again\n") # main method if __name__ == '__main__': # Instantiate the prostudyingInCollegexy bankProxy = BankProxy() # # Client attempting to withdraw all his remaining balance from the bank. bankProxy.debit() # Altering the balance of the account bankProxy.feeBalance = 100 # Client attempting to withdraw the balance of 100 from the bank. bankProxy.debit()
ProBook:~/InfosecAddicts/$ python proxy.py Proxy in action. Checking to see if the balance of student is clear or not... Withdrawal In Progress Money Debited Successfully Proxy in action. Checking to see if the balance of student is clear or not... Insufficient Amount, Please try Again
Pros and Cons
- Open/Closed Principle
- Abstraction Layer
- Increase in complexity
- Slow response