11
Bob TarrDesign Patterns In Java
The Proxy Pattern
21
21
Virtual Proxy Example
Virtual Proxy Example
l Scenario: A Java applet has some very large classes which take a
long time for a browser to download from a web server. How can
we delay the downloading of these classes so that the applet starts
as quickly as possible?
l Solution: Use a Virtual Proxy!
l When using a Virtual Proxy:
é All classes other than the proxy itself must access the target class indirectly
through the proxy. If any class makes a static reference to the target class,
the Java Virtual Machine will cause the class to be downloaded. This is
true even if no instantiation of the target class is done.
Bob TarrDesign Patterns In Java
The Proxy Pattern
22
22
Virtual Proxy Example (Continued)
Virtual Proxy Example (Continued)
l When using a Virtual Proxy (Continued):
é Even the proxy can not make a static reference to the target class initially.
So how does the proxy reference the target class? It must use some form of
dynamic reference to the target. A dynamic reference encapsulates the
target class name in a string so that the Java compiler does not actually see
any reference to the target class and does not generate code to have the
JVM download the class. The proxy can then use the new Reflection API
to create an instance of the target class.
é Both the proxy and the target object implement the same interface which in
Java will be a regular Java interface. Any class can reference this interface,
since the interface definition is small and will be quickly downloaded.