Proxy

The Proxy pattern is used when you need to represent a complex
object by a simpler one. If creating an object is expensive in time or computer
resources, Proxy allows you to postpone this creation until you need the
actual object. A Proxy usually has the same methods as the object it
represents, and once the object is loaded, it passes on the method calls from
the Proxy to the actual object.

 

There are several cases where a Proxy can be useful:
1. If an object, such as a large image, takes a long time to load.
2. If the object is on a remote machine and loading it over the network may
be slow, especially during peak network load periods.
3. If the object has limited access rights, the proxy can validate the access
permissions for that user.
Proxies can also be used to distinguish between requesting an
instance of an object and the actual need to access it. For example, program
initialization may set up a number of objects which may not all be used right
away. In that case, the proxy can load the real object only when it is needed.
Let’s consider the case of a large image that a program needs to load
and display. When the program starts, there must be some indication that an
image is to be displayed so that the screen lays out correctly, but the actual
image display can be postponed until the image is completely loaded. This is
particularly important in programs such as word processors and web browsers
that lay out text around the images even before the images are available.
An image proxy can note the image and begin loading it in the
background, while drawing a simple rectangle or other symbol to represent
the image’s extent on the screen before it appears. The proxy can even delay
loading the image at all until it receives a paint request, and only then begin
the process.

Copy-on-Write

You can also use proxies is to keep copies of large objects that may
or may not change. If you create a second instance of an expensive object, a
Proxy can decide there is no reason to make a copy yet. It simply uses the
original object. Then, if the program makes a change in the new copy, the
Proxy can copy the original object and make the change in the new instance.
This can be a great time and space saver when objects do not always change
after they are instantiated.

Comparison with Related Patterns

Both the Adapter and the Proxy constitute a thin layer around an
object. However, the Adapter provides a different interface for an object,
while the Proxy provides the same interface for the object, but interposes
itself where it can save processing effort.
A Decorator also has the same interface as the object it surrounds, but
its purpose is to add additional (usually visual) function to the original object.
A proxy, by contrast, controls access to the contained class.

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章