Design Pattern: Proxy and Agent

Design Pattern: Proxy and Agent

Design Patterns in life and Ruby — gain an intuitive understanding of OO design patterns by linking them with real-life examples.

Imagine yourself as a movie star, a big one. You are so famous that everyone in Hollywood wants to work with you. You never lack acting opportunities. So many requests come to you that you need an agent to handle them.

Here is what you want your agent to do.

  1. When a new filming request comes, the agent first checks to see if it fits your schedule.
  2. If so, the agent then checks your preferences. (For example, you have been in too many comedies, and you want your next film to be a drama.)
  3. Finally, if the new film fits both your schedule and preferences, the agent sends the request to you and lets you decide if you want to take it or not.


The agent is essentially a proxy that sands in for you.

This is a case calls for the Proxy Pattern.

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

Time for some code


class ActorProxy
  attr_reader :schedule, :preference, :actor
  def initialize(schedule, preference, actor)
    @schedule = schedule
    @preference = preference
    @actor = actor
  def handle(request)
    return 'Sorry, blah blah blah' unless &&
    if actor.wants_to_take(request)
      'We would love to take the opportunity! blah blah blah'
      'Sorry, blah blah blah'

The code for the ActorProxy does exactly what we just described. It handles requests for its actor and only passes a request down when necessary.

Notice the person with a request never deals with you, the actor, directly. Neither do you have to deal with requesters directly.

Revisiting the Definition of Proxy Pattern

The Proxy Pattern provides a surrogate or placeholder for another object to control access to it.

In order to protect your time and privacy, your agent becomes a placeholder for you and limits other people’s access to you. Any request for you has to go through your agent first.

Why we need a proxy

In our example, we need a proxy because as a movie star, your time is limited and expensive. We want you to spend your time filming instead of figuring out your schedule.

In the software world, the Proxy Pattern is commonly used for objects that are either remote, expensive to create, or in need of securing.

Oh! I got a drama film that fits your schedule, would you like to take a look at the script? =)

Subscribe below so you won’t miss the next post!

Enjoyed the article?

My best content on Software Design, Rails, and Career in Dev. Delivered weekly.

Unsubscribe at anytime. I'll never spam you. Powered by ConvertKit

1 Comment Design Pattern: Proxy and Agent

Leave A Comment

Your email address will not be published. Required fields are marked *