Head First Design Patterns : 10 of 10 ( Proxy Pattern)

sanmiade

Oluwasanmi Aderibigbe

Posted on September 12, 2021

Head First Design Patterns : 10 of 10 ( Proxy Pattern)

I just learnt a new design from the Head First Design Pattern book. Today, I learnt about the State pattern.

According to The head first design pattern, the Proxy pattern is used to provide a placeholder for another object to control access to it. It also allows you to perform actions before or after calls have been made to the real object.

Types of Proxy:

1 Remote proxy: A remote proxy is a kind of proxy that acts as a local representative of an object that lives in a different JVM. Method calls to a remote proxy are transferred over the wire and invoked, and the result being returned to the proxy and then to the client.

2 Virtual Proxy: A virtual proxy is a kind of proxy that acts as a representative for an object that is expensive to create. Virtual proxies defer the creation of the real object until it is needed.

3 Protection Proxy: A protection proxy is a kind of proxy that is used to restrict access to confirm calls to the real object.

4 Cache Proxy: A cache proxy is a kind of proxy that caches data returned by the real object so later calls to return the cached data.

5 Log Proxy: A Logging proxy is a kind of proxy that is used to logs requests to the real object before or after.

Implementing a proxy is rather simple. Proxy is a wrapper around the real object with the same base type as the real object.

interface Money

class Cash : Money {
  fun makePayment(){ }
}

class ATMCard(val cash: Cash) : Money {
    fun makePayment() {
         if (checkTime()) {
             cash.makePayment()
         } else {
             throw  IllegalArgumentException("You can not use an atm at this time")
         }
    }

    fun checkTime() : Boolean
}
Enter fullscreen mode Exit fullscreen mode
  1. The first thing you need to do is setup up your marker interface or abstract class.
  2. Make the real object and the proxy implement the same type.
  3. Make the proxy wrapper the real object and delegate calls to it.

The example above is a protection proxy. It validates calls to the real object before delegating them to the real object.
This design pattern is somewhat similar to the Decorator design pattern in implementation. The proxy pattern is used to control access to the real object while the Decorator pattern is used to add new behaviour to the object.

đź’– đź’Ş đź™… đźš©
sanmiade
Oluwasanmi Aderibigbe

Posted on September 12, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related