Proxy Design Pattern in Swift
Tags: swift, ios, designpatterns, architecture
Published: 2023-08-07 15:17:51

## Preface

Nearly all actual projects don’t require us to write every module from scratch; instead, we use third-party libraries to solve our issues, speed up development, and let us focus on our key features.

In order to use the features of third-party libraries, especially when importing them as modules through Cocoapod or SPM, you must import them everywhere.

Imagine, however, that after using [Kingfisher](https://github.com/onevcat/Kingfisher) for image loading for a while, you find that [Nuke](https://github.com/kean/Nuke) or [SDWebImage](https://github.com/SDWebImage/SDWebImage) performs much better for your needs.

If this is the case, you must replace the old module with the new one in all of your files. the situation will get even worse when you have to replace or remove all of the old module functions from your project because you are using so many of them.

In such a case, you can use the **Proxy** **design** **pattern** as a savior.

&nbsp;

![savior mime](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbnbanga813l6zj6u2z5.gif)

---

## Definition
&nbsp;
The proxy design pattern is a structural design pattern that we use to provide a placeholder for another object and control access to it.

To explain it better, first, take a look at the logical diagram of proxy:


![logical diagram of proxy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85mu8wkauco99woo7rai.png)

As you can see, we have blocked all client access to the real object since they can only communicate with the proxy object. with this approach, we **protect** and **hide** all of the real object’s functions and variables from other project components.

---

## Applicability
&nbsp;
In general, there are three different types of proxy design patterns:

&nbsp;

**Remote proxy**: Represents actual objects in a different space. for example, REST APIs create objects on the server, and clients use REST requests to access those objects.

![remote proxy image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mcw2yzbcaw0w71h2fg5a.png)

&nbsp;

**Virtual proxy**: Creates expensive objects on demand.in this approach, proxy objects stand as a substitute for the real object but act in a different way to delay its creation.


![virtual proxy image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7hwueiqfrmdxlg125wr.png)

&nbsp;

**Protection proxy**: controls access to the real object. the protection proxy is also useful when the real object needs various access roles for every client object or component.


![protection proxy image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xlckiknb3qimhzdsr1h.png)

---

## Implementation
&nbsp;
First, let me show the **remote** proxy in the code:


![implementation api image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sdi0jhuadz7jpbkqftt.png)

As you can see from the code, the real object was created on the server side and sent to the client after serialization. It wasn’t created in our app. The client obtained this object, deserialized it, and used it within the app. If we assume that the client only requests updates or receives the most recent value, then the **user** object is a remote proxy object, and the API class serves as our proxy to access the user object.

Next, let's look at the **virtual** proxy in the code:

&nbsp;
![virtual proxy image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xjjkuuw9r1lwsi49lch7.png)

&nbsp;

As you can see from the code above, the placeholder image is returned if the getImage function is called before the image is prepared to display. Until the actual image process (downloading or drawing) is complete, a placeholder image is a virtual object that stands in for a real image. Following that, calling the getImage or getSize functions will result in a real image being returned.

Finally, we must specify how other objects can access our actual objects in order to implement a **protection** proxy.

As we discussed in the introduction to this article, let’s solve the image loader issue. This problem can be resolved by first using a protocol to specify how other objects can access our image loader.

&nbsp;
![protection proxy image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nlv87v8nxbnqx67jwfen.png)
&nbsp;

As you see, all input and output of the _loadImage_ function are Swift features or Apple’s first-party libraries for the iOS platform (like UIKit).

&nbsp;
![ImageLoaderPorotocol image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/23uh6wsas76vnce45tz9.png)
&nbsp;

Now, we create another file and import the required third-party library inside it and implement _ImageLoaderPorotocol_.

You can even use this technique when using **RxSwift** or **Combine**. here is an example of the RxSwift version:

&nbsp;
![rx image proxy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y820p7rs5uxzaabtyott.png)
&nbsp;

As you can see, the codes above use the Nuke image loader but instead return a regular image.

With this method, we don’t have to import Nuke into each and every file that needs to load an image, and you can swap out the Nuke library whenever you like with any other image loader by simply implementing the ImageLoaderProtocol function with a new image loader library (like KingFisher or SDWebImage).

---

## FAQ

&nbsp;
### When should we use the proxy design pattern?

Proxy design patterns are typically used when we try to limit access to a specific object via API and hide it from other parts of a project (protection proxy). but as you can see in the example above, you can use proxy design patterns when you want to virtualize your real object with a placeholder to defer the real object’s cost of creation (virtual proxy) or use an object that is placed in another space rather than your code (remote proxy).

&nbsp;
### What’s different between the Proxy and Decorator design patterns? (Proxy vs Decorator)


While the Decorator design pattern wraps the real object and gives it more responsibility, the primary purpose of using a proxy design pattern is to hide and conceal the real object from clients.

&nbsp;
### What’s different between the Proxy and Adaptor design patterns? (Proxy vs Adaptor)


The adaptor design pattern is primarily used to adapt to incompatible and legacy codes. It wraps and provides a different interface for the real object.

For example, if your app uses multiple login methods (such as Google, Apple, Facebook, etc.), all of them must confirm the login protocol. By using this method, you can communicate with your login systems effectively and without a boilerplate.

&nbsp;
### What’s different between Proxy and facade design patterns? (Proxy vs facade)

The facade design pattern is primarily used to simplify the use of complex objects or libraries. While a proxy will wrap only one object to control access to it, a facade wraps one or more objects to simplify their complex behavior or creation.

In summary, the facade reduces communication and dependencies between objects, whereas the proxy serves as a bridge between the client and the wrapped object.

---

 My [Github](https://github.com/Ali72)
 My [Personal website](https://ali72.github.io/)