A proxy is an object that controls access to another object. For example, it is possible to call your top executive, the CEO of your company, directly and make an appointment with them. However, the CEO is very busy and in order for them to function efficiently, you would call their assistant and make an appointment with them instead.
The assistant controls access to the CEO. You can think of them as the proxy for the CEO. They queue up appointments, prevent unnecessary appointments, and they even keep track of who met with the CEO. There are a number of reasons to use a proxy, but the main motivation from the design pattern has to do with expensive objects.
Instead of working directly with an object that requires a lot of resources, you can work with a proxy, an object that has the exact same interface, but the proxy can delay instantiation of an expensive object and control requests made to that object.
The gang of four defines the intent of a proxy as providing a surrogate or placeholder for another object to control access to it. In addition to managing expensive objects, proxies can be used to manage a remote resource, provide data validation of input, provide security, cache data, even log actions.
Just like the adapter pattern, a proxy must provide the same interface as the subject. The client would call the same methods on the proxy that they would call on the original object.Let’s create a proxy that will control access to the file system. So within the exercise files, under chapter three lesson three within the start folder, we have an index.js file that is readingtwo files and writing the results to the console. So what this file actually does is it links to both a text and a markdown file and then it reads both of those files. So we set up the paths to those files on line four and five, we have a generic call back function for the result.
Then we’ll check and see if we have an error, but if we don’t have an error it will go ahead and log the contents of the files that we’re reading on line 16. Line 20 and 21 we’re reading both the text and markdown files. So let’s go over to the terminal and takes a look at what this looks like. Node index.js. So our current code can read both files. In the next lesson, we’re going to go ahead and create a file system proxy that will prevent us from being able to read any files with a text extension.