A Design Pattern Story in Swift – Chapter 12: Proxy
07 Jul 2015
Life is too short to do everything by ourselves, so we often let others do things for us.
When the good people of the village need their own cat pets, they go to different proxies. The proxies would then do some god-knows-what kind of trick and get the villagers some cats.
First, it’s the entry-level Simple Cat Proxy called – “SimpleCatRequestProxy”. You request a cat and he’ll get a cat from the remote cat house.
The next is the Clone (cache) Cat Proxy. He will create a local clone once he got a cat from the remote cat house. When others request the cat, he will first look at his cloned list. If the clone exists, he will return a clone. If not, he will get the cat from the remote cat house.
The third one is Batch (Virtual) Cat Proxy. When people request cats, he simply writes down their requests and later fetch the cats from remote cat house in a big batch.
The first Batch Cat Proxy always retrieves the same cats remotely but people want different cats. So they go to the batch unique cat proxy, who keeps a number of different options of cats.
The last one is the Secure(Protection) Proxy. He is always quite serious and have to check everybody’s “passcode” before giving them any cats.
The rest of the code:
The proxy pattern is used to provide a surrogate or placeholder object, which references an underlying object. The proxy provides the same public interface as the underlying subject class, adding a level of indirection by accepting requests from a client object and passing these to the real subject object as necessary. — Gang Of Four
More info:
Remote Proxy – Represents an object locally which belongs to a different address space. Think of an ATM implementation, it will hold proxy objects for bank information that exists in the remote server.
Virtual Proxy – In place of a complex or heavy object, use a skeleton representation. When an underlying image is huge in size, just represent it using a virtual proxy object and on demand load the real object. You know that the real object is expensive in terms of instantiation and so without the real need we are not going to use the real object. Until the need arises we will use the virtual proxy.
Protection Proxy – Are you working on an MNC? If so, we might be well aware of the proxy server that provides us internet by restricting access to some sort of websites like public e-mail, social networking, data storage etc. The management feels that, it is better to block some content and provide only work related web pages. Proxy server does that job. This is a type of proxy design pattern. — Wiki