Photo by Brett Jordan on Unsplash

Provide a placeholder for another object

Swift — Problems Catalogue #9

Alex Ilovan
Published in
3 min readAug 12, 2022

--

Problem Definition:

Consider the following scenario. You must implement a War Video Game App that lets you communicate with your base and ally base among others. But wait! The enemy base can always proxy your wire and intercept your entire communications line or establish a communication line and pretend they are you 😮🫢

Fun fact: in the computer security field, there is an attack that utilizes the exact same concept of interposing between two computers comunicating with each other and intercepting their entire conversation. It’s called the Man-in-the-middle.

Problem Solution:

Solution — Proxy is a structural design pattern that provides an object as a placeholder for another object that provides an actual service.

In general a Proxy, in essence, takes a request from a client, performs some different tasks like load balancing, and access control and then afterwards passes the request to the object that provides the actual service.

*Disclaimer

Usually, in mobile apps, this particular design pattern is quite rare. It’s usually used as an architectural pattern at the infrastructure level but for the fun of it, let’s implement one.

Real-World Usage:

Let’s start by creating a protocol called Base with a simple method that grants the ability to call().

Next, we need to create two classes, the AllyBase and also the EnemyBase. Afterwards, we conform both classes to the Base protocol and implement the call method.

Now, for the proxy part. In this scenario, the EnemyBase is basically the Proxy referred to in this article and we just need to take a reference to an AllyBase and from there we can perform a call to it with some added spiciness (*laughs in enemy)

Figure 1. Bases

Next, we define our Headquarters and the method to execute a call to a particular base.

Last but not least, let’s define our WarApp. As you can see, here the Proxy shines, it can be used interchangeably with a base object thus providing a placeholder to use in which you can add extra business logic.

Figure 2. The WarApp

From this point on, the sky is the limit 🚀 well…almost.

Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.

This is the next article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.

Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶

--

--

Alex Ilovan
salt&pepper

🚀Head of Mobile Development @S&P 💻Comp. Engineer 🪐Engineering Manager. You can visit at: https://www.linkedin.com/in/alex-ilovan-129161b4/