2. ProblemsProblems
You need to control access to an objectYou need to control access to an object
Defer the cost of object creation andDefer the cost of object creation and
initialization until actually usedinitialization until actually used
3. SolutionSolution
Create a Proxy object that implements theCreate a Proxy object that implements the
same interface as the real objectsame interface as the real object
The Proxy object contains a reference to theThe Proxy object contains a reference to the
real objectreal object
Clients are given a reference to the Proxy, notClients are given a reference to the Proxy, not
the real objectthe real object
All client operations on the object pass throughAll client operations on the object pass through
the Proxy, allowing the Proxy to performthe Proxy, allowing the Proxy to perform
additional processingadditional processing
4. Proxy PatternProxy Pattern
Acts as an intermediary between the client and the targetActs as an intermediary between the client and the target
objectobject
Why? Target may be inaccessible (network issues, too large toWhy? Target may be inaccessible (network issues, too large to
run, resources…)run, resources…)
Has the same interface as the target objectHas the same interface as the target object
The proxy has a reference to the target object and forwardsThe proxy has a reference to the target object and forwards
(delegates) requests to it(delegates) requests to it
Useful when more sophistication is needed than a simpleUseful when more sophistication is needed than a simple
reference to an object (i.e. we want to wrap code aroundreference to an object (i.e. we want to wrap code around
references to an object)references to an object)
Proxies are invisible to the client, so introducing proxiesProxies are invisible to the client, so introducing proxies
does not affect client codedoes not affect client code
5. Proxy patternProxy pattern
Interface inheritance is used to specify the interfaceInterface inheritance is used to specify the interface
shared byshared by ProxyProxy andand RealSubject.RealSubject.
Delegation is used to catch and forward any accesses toDelegation is used to catch and forward any accesses to
thethe RealSubjectRealSubject (if desired)(if desired)
Proxy patterns can be used for lazy evaluation and forProxy patterns can be used for lazy evaluation and for
remote invocation.remote invocation.
Subject
Request()
RealSubject
Request()
Proxy
Request()
realSubject
6. 6
Proxy PatternProxy Pattern
Types of ProxiesTypes of Proxies
Virtual Proxy / Cache ProxyVirtual Proxy / Cache Proxy: Create an: Create an
expensive object on demand (lazyexpensive object on demand (lazy
construction) / Hold results temporarilyconstruction) / Hold results temporarily
Remote ProxyRemote Proxy: Use a local representative for: Use a local representative for
a remote object (different address space)a remote object (different address space)
Protection ProxyProtection Proxy: Control access to shared: Control access to shared
objectobject
7. Virtual Proxy ExamplesVirtual Proxy Examples
Object-Oriented DatabasesObject-Oriented Databases
Objects contain references to each otherObjects contain references to each other
Only load the real object from disk if a method is neededOnly load the real object from disk if a method is needed
Resource ConservationResource Conservation
Save memory by only loading objects that are actually usedSave memory by only loading objects that are actually used
Objects that are used can be unloaded after awhile, freeing upObjects that are used can be unloaded after awhile, freeing up
memory (Can also be Cached Proxy)memory (Can also be Cached Proxy)
Word ProcessorWord Processor
Documents that contain lots of multimedia objects should still loadDocuments that contain lots of multimedia objects should still load
fastfast
Create proxies that represent large images, movies, etc., and onlyCreate proxies that represent large images, movies, etc., and only
load objects on demand as they become visible on the screenload objects on demand as they become visible on the screen
8. Image Proxy (1 or 3)Image Proxy (1 or 3)
interface Image {
public void displayImage();
}
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
System.out.println("Loading "+filename);
}
public void displayImage() { System.out.println("Displaying "+filename); }
}
9. Image Proxy (2 of 3)Image Proxy (2 of 3)
class ProxyImage implements Image {
private String filename;
private RealImage image = null;
public ProxyImage(String filename) { this.filename = filename; }
public void displayImage() {
if (image == null) {
image = new RealImage(filename); // load only on demand
}
image.displayImage();
}
}
10. Image Proxy (3 of 3)Image Proxy (3 of 3)
class ProxyExample {
public static void main(String[] args) {
ArrayList<Image> images = new ArrayList<Image>();
images.add( new ProxyImage("HiRes_10GB_Photo1") );
images.add( new ProxyImage("HiRes_10GB_Photo2") );
images.add( new ProxyImage("HiRes_10GB_Photo3") );
images.get(0).displayImage(); // loading necessary
images.get(1).displayImage(); // loading necessary
images.get(0).displayImage(); // no loading necessary; already done
// the third image will never be loaded - time saved!
}
}
13. 13
ForcesForces
1. The image is expensive to load1. The image is expensive to load
2. The complete image is not always2. The complete image is not always
necessarynecessary
2MB 2KB
optimize!
16. Remote ProxyRemote Proxy
The Client and Real Subject are in different processesThe Client and Real Subject are in different processes
or on different machines, and so a direct method callor on different machines, and so a direct method call
will not workwill not work
The Proxy's job is to pass the method call acrossThe Proxy's job is to pass the method call across
process or machine boundaries, and return the resultprocess or machine boundaries, and return the result
to the client (with Broker's help)to the client (with Broker's help)
17. Protection ProxyProtection Proxy
Different clients have different levels of accessDifferent clients have different levels of access
privileges to an objectprivileges to an object
Clients access the object through a proxyClients access the object through a proxy
The proxy either allows or rejects a method callThe proxy either allows or rejects a method call
depending on what method is being called anddepending on what method is being called and
who is calling it (i.e., the client's identity)who is calling it (i.e., the client's identity)
18. Additional UsesAdditional Uses
Read-only CollectionsRead-only Collections
Wrap collection object in a proxy that only allows read-onlyWrap collection object in a proxy that only allows read-only
operations to be invoked on the collectionoperations to be invoked on the collection
All other operations throw exceptionsAll other operations throw exceptions
List Collections.unmodifiableList(List list);List Collections.unmodifiableList(List list);
Returns read-only List proxyReturns read-only List proxy
Synchronized CollectionsSynchronized Collections
Wrap collection object in a proxy that ensures only one thread atWrap collection object in a proxy that ensures only one thread at
a time is allowed to access the collectiona time is allowed to access the collection
Proxy acquires lock before calling a method, and releases lockProxy acquires lock before calling a method, and releases lock
after the method completesafter the method completes
List Collections.synchronizedList(List list);List Collections.synchronizedList(List list);
Returns a synchronized List proxyReturns a synchronized List proxy