design-patterns/structural/proxy/README.md
Ruidy 18dc62563c
Proxy (#13)
* doc: add proxy README documentation

* doc: edit general README files

* add proxy code example

Co-authored-by: Ruidy <r.nemausat@empfohlen.de>
2020-09-29 21:08:07 +02:00

2.6 KiB
Raw Blame History

Proxy

Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.

Problem

Why would you want to control access to an object? Here is an example: you have a massive object that consumes a vast amount of system resources. You need it from time to time, but not always.

You could implement lazy initialization: create this object only when its actually needed. All of the objects clients would need to execute some deferred initialization code. Unfortunately, this would probably cause a lot of code duplication.

In an ideal world, wed want to put this code directly into our objects class, but that isnt always possible. For instance, the class may be part of a closed 3rd-party library.

Solution

The Proxy pattern suggests that you create a new proxy class with the same interface as an original service object. Then you update your app so that it passes the proxy object to all of the original objects clients. Upon receiving a request from a client, the proxy creates a real service object and delegates all the work to it.

But whats the benefit? If you need to execute something either before or after the primary logic of the class, the proxy lets you do this without changing that class. Since the proxy implements the same interface as the original class, it can be passed to any client that expects a real service object.

How to Implement

  1. If theres no pre-existing service interface, create one to make proxy and service objects interchangeable. Extracting the interface from the service class isnt always possible, because youd need to change all of the services clients to use that interface. Plan B is to make the proxy a subclass of the service class, and this way itll inherit the interface of the service.

  2. Create the proxy class. It should have a field for storing a reference to the service. Usually, proxies create and manage the whole life cycle of their services. On rare occasions, a service is passed to the proxy via a constructor by the client.

  3. Implement the proxy methods according to their purposes. In most cases, after doing some work, the proxy should delegate the work to the service object.

  4. Consider introducing a creation method that decides whether the client gets a proxy or a real service. This can be a simple static method in the proxy class or a full-blown factory method.

  5. Consider implementing lazy initialization for the service object.