Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science 209 The Proxy Pattern. Delayed Instantiation if (obj == null) obj = It ’ s expensive to load an image If the user never looks at an image,

Similar presentations


Presentation on theme: "Computer Science 209 The Proxy Pattern. Delayed Instantiation if (obj == null) obj = It ’ s expensive to load an image If the user never looks at an image,"— Presentation transcript:

1 Computer Science 209 The Proxy Pattern

2 Delayed Instantiation if (obj == null) 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

3 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

4 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 }

5 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

6 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

7 The Proxy Setup > Subject Proxy Client request() RealSubject request()

8 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


Download ppt "Computer Science 209 The Proxy Pattern. Delayed Instantiation if (obj == null) obj = It ’ s expensive to load an image If the user never looks at an image,"

Similar presentations


Ads by Google