Proxy Pattern

Problem: sometimes some objects consume a lot of resources and can be a problem at startup. What you do is not create those objects until there are needed or a request has come for them. An example is a database connection.

Problem solved by Proxy pattern

Solution

Solution with the Proxy pattern

Proxy is a placeholder for another object. A proxy controls access to the original object and allows actions to take place either before or after a request gets through to the original object.

Proxy design pattern

Applicability

Lazy initialization (virtual proxy). This is when you have a heavyweight service object that wastes system resources by being up always, even though you only need it from time to time.

Instead of creating the object when the app launches, you can delay the object’s initialization to a time when it’s really needed.

Access control (protection proxy). This is when you want only specific clients to be able to use the service object; for instance, when your objects are crucial parts of an operating system and clients are various launched applications (including malicious ones).

The proxy can pass the request to the service object only if the client’s credentials match some criteria.

Local execution of a remote service (remote proxy). This is when the service object is located on a remote server.

In this case, the proxy passes the client request over the network, handling all of the nasty details of working with the network.

Logging requests (logging proxy). This is when you want to keep a history of requests to the service object.

The proxy can log each request before passing it to the service.

Caching request results (caching proxy). This is when you need to cache results of client requests and manage the life cycle of this cache, especially if results are quite large.

The proxy can implement caching for recurring requests that always yield the same results. The proxy may use the parameters of requests as the cache keys.

Smart reference. This is when you need to be able to dismiss a heavyweight object once there are no clients that use it.

The proxy can keep track of clients that obtained a reference to the service object or its results. From time to time, the proxy may go over the clients and check whether they are still active. If the client list gets empty, the proxy might dismiss the service object and free the underlying system resources.

The proxy can also track whether the client had modified the service object. Then the unchanged objects may be reused by other clients.

A real-world example of proxy can be a cheque or credit card for what is in your bank account. A credit card can be used as a placeholder for cash and provides a means of accessing that cash when required. And that’s exactly what the Proxy pattern does – “Controls and manages access to the actual object”.

public class BankAccount {

	private long id;
	private String routingNumber;
	private String accountNumber;
	private String name;
	private double balance;
	private double transferFee;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getRoutingNumber() {
		return routingNumber;
	}
	public void setRoutingNumber(String routingNumber) {
		this.routingNumber = routingNumber;
	}
	public String getAccountNumber() {
		return accountNumber;
	}
	public void setAccountNumber(String accountNumber) {
		this.accountNumber = accountNumber;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getBalance() {
		return balance;
	}
	public void setBalance(double balance) {
		this.balance = balance;
	}
	public double getTransferFee() {
		return transferFee;
	}
	public void setTransferFee(double transferFee) {
		this.transferFee = transferFee;
	}
	public boolean withdraw(double amount) {
		if(balance>0 && balance>=amount) {
			balance-=amount;
			return true;
		}
		throw new RuntimeException("Nothing enough funds in your account.");
	}	
}

public class CreditCard {
	
	// credit card number
	private String number;
	private String cvc;
	private String expMonth;
	private String expYear;
	private String zipcode;
	private String last4;

	BankAccount bankAccount;

	public CreditCard() {
		this(null);
	}

	public CreditCard(BankAccount bankAccount) {
		this(null,null,null,null,null,null,bankAccount);
	}



	public CreditCard(String number, String cvc, String expMonth, String expYear, String zipcode, String last4,
			BankAccount bankAccount) {
		super();
		this.number = number;
		this.cvc = cvc;
		this.expMonth = expMonth;
		this.expYear = expYear;
		this.zipcode = zipcode;
		this.last4 = last4;
		this.bankAccount = bankAccount;
	}
	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public String getCvc() {
		return cvc;
	}

	public void setCvc(String cvc) {
		this.cvc = cvc;
	}

	public String getExpMonth() {
		return expMonth;
	}

	public void setExpMonth(String expMonth) {
		this.expMonth = expMonth;
	}

	public String getExpYear() {
		return expYear;
	}

	public void setExpYear(String expYear) {
		this.expYear = expYear;
	}

	public String getZipcode() {
		return zipcode;
	}

	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	public String getLast4() {
		return last4;
	}

	public void setLast4(String last4) {
		this.last4 = last4;
	}

	public BankAccount getBankAccount() {
		return bankAccount;
	}

	public void setBankAccount(BankAccount bankAccount) {
		this.bankAccount = bankAccount;
	}	
}

public class CreditCardService {

	public boolean authorizeCharge(CreditCard creditCard, double amount) {
		return creditCard.getBankAccount().withdraw(amount);
	}

	public double getAvailableBalance(CreditCard creditCard) {
		// TODO Auto-generated method stub
		return creditCard.getBankAccount().getBalance();
	}
}

public class ProxyDemo {
	
	static CreditCardService creditCardService = new CreditCardService();

	public static void main(String[] args) {
		BankAccount bankAccount = new BankAccount();
		bankAccount.setId(1);
		bankAccount.setAccountNumber("000123456789");
		bankAccount.setRoutingNumber("110000000");
		bankAccount.setBalance(1000);
		bankAccount.setName("Laulau");
		
		CreditCard masterCard = new CreditCard(bankAccount);
		
		// charge $100;
		double chargeAmount = 100;
		
		double availableBalance = creditCardService.getAvailableBalance(masterCard);
		
		System.out.println("availableBalance: $"+availableBalance);
		
		boolean ok = creditCardService.authorizeCharge(masterCard, chargeAmount);
		
		System.out.println("charge ok? "+ok);
	}
}

Pros

  • You can control the service object without clients knowing about it.
  •  You can manage the lifecycle of the service object when clients don’t care about it.
  •  The proxy works even if the service object isn’t ready or is not available.
  •  Open/Closed Principle. You can introduce new proxies without changing the service or clients.

Cons

  •  The code may become more complicated since you need to introduce a lot of new classes.
  •  The response from the service might get delayed.

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.