Flyweight and Proxy Design Patterns

By Mike Heinrich and Philip Kunsik Cho

PowerPoint Presentation

Flyweight

Proxy

References

Flyweight

Description
Class Diagram
General Points and Terminology

Example 1: Folder Example
Example 2: Tone Generator Pool

Related Patterns
Conclusion

Description

provides a way to limit the proliferation of small, simliar class instances by moving some of the class data outside the class and passing it in during various execution methods. (Cooper, 1998)

Flyweight Class Diagram

(Kremer, 2002)
Flyweight Class Diagram

General Points and Terminology

Examples

Example 1: Folders

(Cooper, 1998)

We want to draw a small folder icon with a name under it for each person in an organization. This means no matter the number of icons it is the same graphical image. If we have two icons, one for "isSelected" and one for "notSelected" we have limited our use of resources. A FolderFactory class is created that returns either the selected or unselected folder drawing class. The FolderFactory class does not create additional instances once one of each of them has been created. In the following code example, both instances are created at the outset and then one or the other is returned.

FolderFactory Class
class FolderFactory
{
Folder unSelected, Selected;
public FolderFactory()
  {
    Color brown = new Color(0x5f5f1c);
    Selected = new Folder(brown);
    unSelected = new Folder(Color.yellow);
  }
//-------------------------------------
public Folder getFolder(boolean isSelected)
  {
    if(isSelected)
      return Selected;
    else
      return unSelected;
  }
}


If more instances existed, the FolderFactory could keep a table of the instances already created and only create new instances if they aren't in the table. The extrinsic data in this case is the name attached to the folder and the co-ordinates of the folder. The Folder class creates an instance with one of two background colours and the public Draw method draws the folder at the co-ordinates specified.


Folder Class
class Folder extends JPanel
{
  private Color color;
  final int W = 50, H = 30;
  public Folder(Color c)
    {
      color = c;
    }
//------------------------------------------------------
public void Draw(Graphics g, int tx, int ty, String NAME)
   {
   g.setColor(Color.black);     ;//outline
    g.drawRect(tx, ty, W, H);
    g.drawString(name, tx, ty + H + 15);   //title

    g.setColor(color);      //fill rectangle
    g.fillRect(tx+1, ty+1, W-1, H-1);

    g.setColor(Color, lightGray);     //bend line     g.drawLine(tx+1, ty+H-5, tx+W-1, ty+H-5);

    g.setColor(Color.black);     //shadow lines
    g.drawLine(tx, ty+H+1, tx+w-1, ty+H+1);
   g.drawLine(tx+w+1, ty, tx+W+1, ty+H);

   g.setColor(Color.white);     //highlight lines    g.drawLine(tx+1, ty+1, tx+W-1, ty+1);
   g.drawLine(tx+1, ty+1, tx+1, ty+H-1);
   }
}

For the purpose of these notes, the paint and mouseMoved events will not be defined. All of the classes can be viewed at the James Cooper's website. This example shows how the Flyweight design pattern can be used to minimize system resources by decreasing the number of unique instances of a class.


Example 2: Tone Generator Pool

(Duell, 2002)
Flyweight Example in Telecommunications


Telecommunications often has problems similar to problems which must be solved in Computer Science. In this case, the tone generator pool can use the Flyweight design pattern. Here:

When a tone generator is requested, it is connected to the A party (the subscriber line). When the tone is no longer needed, it is disconnected so that another client can use it. The switch maintains the reference to the flyweights. The Flyweight design pattern is intended to save cost in this case by reducing the number of tone generators required and reducing the physical space required for equipment.



Related Patterns

Flyweight is often combined with the Composite pattern to implement a directed-acyclic graph with shared leaf nodes. State and Strategy should often be implemented as Flyweights. (Gamma, 1995)


Conclusion

Flyweight introcuces run-time costs associated with transferring, finding, and/or computing extrinsic states. The costs introduced by the Flyweight pattern are offset by space savings. Storage savings are influenced by several factors:

The more intrinsic states there are, the more savings occur. If a large number of extrinsic states must be computed, the space savings occur at the expense of computation time.


The Flyweight design pattern is intended to use sharing to support large numbers of objects efficiently. Flyweight should be used in cases where many objects share simliar data except for a few items, which can be passed through parameters. A Flyweight has both an intrinsic and an extrinsic state. The instrinsic state is stored in the Flyweight and consists of information that is independent of the Flyweight's context. The extrinsic state is stored in the client. The extrinsic state is the parameters that are passed into the methods. Flyweight offsets run-time costs with storage savings.



Proxy

Description
Class Diagram
General Points and Terminology

Example 1: Image Proxy
Example 2: 800 Number

Related Patterns
Conclusion

Description

used when you need to represent a complex object by a simpler one (Cooper, 1998)

Proxy Class Diagram

(Kremer, 2002)
Proxy Class Diagram

General Points and Terminology

Several cases where a Proxy can be useful:
  1. If an object takes a long time to load
  2. If the object is on a remote machine and loading it over a network may be slow
  3. If the object has limited access rights, the proxy can authenticate a user (Cooper, 1998)

Example 1: Image Proxy

(Cooper, 1998)

We want to display an image on a JPanel when it is loaded. The loading will be deferred to the class ImageProxy which draws a rectangle around the image area until the loading is complete.

ProxyDisplay Class

public class ProxyDisplay extends JxFrame
{
 public ProxyDisplay()
 {
 super("Display proxied image");
 JPanel p = new JPanel();
 getContentPane().add(p);
 p.setLayout(new BorderLayout());
 ImageProxy image = new ImageProxy(this, "elliot.jpg", 321,271);
 p.add("Center", image);  setSize(400,400);  setVisible(true); }

The instance of ImageProxy is created and added to the JPanel in exactly the same way as an actual image. ImageProxy starts the loading process and creates a MediaTracker object to follow the loading process within the constructor:

ImageProxy Class

public ImageProxy(JFrame f, String filename, int w, int h)
{
height = h;
width = w;
frame = f;

tracker = new MediaTracker(f);
img = Toolkit.getDefaultToolkit().getImage(filename);
tracker.addImage(img, 0);   //watch for image loading

imageCheck = new Thread(this);
imageCheck.start();    //start 2nd thread monitor

//this begins the actual image loading
try{
   tracker.waitForId(0,1);
  {
catch(InterruptedException e){}
}

The waitForID method actually initiates loading. In this case, the minimum wait time is 1 millisecond to minimize the apparent program delays. The constructor also creates a thread to check the loading staus every few milliseconds. This code can be found at at the James Cooper's website. This example illustrates how the ImageProxy class acts as a placeholder for a more complex image until the object has completed processing.

Example 2: 800 Number

(Duell, 2002)
800 Number Image


Again we can look to the telecommunications for an example of an everyday use of a design pattern. Here, the Proxy pattern applies. In this case:

Proxy introduces a level of indirection when accessing an object. This indirection can be used for security or to forward the information to a different address space. In this case, the proxy acts as a remote proxy which hides the actual number being dialed.


Related Patterns

(Gamma, 1995)

Adapter provides a different interface to the object it adapts, while proxy provides the same interface as its subject. A proxy's interface can be a subset of its subject's.
Decorators can have simliar implementations as proxies but they have a different purpose. A decorator adds one or more responsibilites to an object, whereas a proxy controls access to an object.


Conclusion

Proxy has effectively 3 uses:

  1. a remote proxy which hides the fact that an object resides in a different obejct space.
  2. a virtual proxy which can perform optimizations such as creating an object on demand.
  3. protection proxies allow additional housekeeping tasks when an object is accessed.

Proxy is highly useful in all three forms. Its use as a memory-saving object allows for faster applications and it's use as a remote object allows for more secure applications.

References

Cooper, James W. The Design Patterns Java Companion. IBM Thomas J. Watson Research Center. Yorkton Heights, NY, 1998. http://www.patterndepot.com/put/8/JavaPatterns.htm

Duell, Michael. Non-Software Examples of Software Design Patterns. Accessed March 9, 2002, from http://www.agcs.com/supportv2/techpapers/patterns/papers/tutnotes/index.htm

Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Professional Computing Series, Addison-Wesley, Reading Mass. 1995.

Kremer, Rob. Design Pattern Notes. Accessed March 18, 2002, from http://sern.ucalgary.ca/courses/seng/443/w02/patterns/index.html



Created by:   Mike Heinrich
Comments? Email Me
Last Updated:   March 18, 2002
This page has been tested on Opera, Internet Explorer, Lynx, Netscape, and Mozilla.

Valid XHTML 1.0!