Computer Science 209 The Proxy Pattern. Delayed Instantiation if (obj == null) obj = It ’ s...
-
Upload
katherine-wade -
Category
Documents
-
view
217 -
download
3
Transcript of Computer Science 209 The Proxy Pattern. Delayed Instantiation if (obj == null) obj = It ’ s...
Computer Science 209
The Proxy Pattern
Delayed Instantiation if (obj == null) obj = <get the object from whatever source>
<use obj>
It’s expensive to load an image
If the user never looks at an image, don’t load it
Load the image when the user needs to look at it
Especially effective when there are lots of images
Use a Proxy Object
// Load the image at instantiation, which can be expensive
JLabel label = new JLabel(new ImageIcon(imageName));
// Or delay loading until painting, which is cheaper
JLabel label = new JLabel(new ImageProxy(imageName));
ImageProxy implements the Icon interface just like ImageIcon, but delays loading until paintIcon is called
Implementing the Proxy Class public class ImageProxy implements Icon{
private String name; private ImageIcon image;
public ImageProxy(String n){ name = n; }
public void paintIcon(Component c, Graphics g, int x, int y){ if (image == null) image = new ImageIcon(name); image.paintIcon(c, g, x, y); }
// Other Icon methods}
The Context of the Proxy Pattern
• A class (the real subject) provides a service specified by an interface type (the subject)
• The service must be modified to make it more versatile
• Neither the client nor the subject should be affected by the modification
Solution of the Proxy Pattern
• Define a proxy class that implements the subject interface
• The proxy holds a reference to the real subject or knows how to locate it
• The client uses a proxy object
• Each proxy method invokes the same method on the real subject and provides the necessary modifications
The Proxy Setup
<<Interface>>Subject
Proxy
Client
request()
request()
RealSubject
request()
Another Example: A Sorted List
• A sorted list includes all of the methods in the List interface
• Some methods, such as add(i) and set(i), are not supported
• Other methods, such as add(obj) and contains(obj) are modified to enforce the natural ordering of elements or to improve the efficiency of searches
• The sorted list holds a reference to a list and calls the corresponding methods for the most part