{"id":1312,"date":"2012-01-08T18:21:10","date_gmt":"2012-01-08T23:21:10","guid":{"rendered":"http:\/\/unitstep.net\/?p=1312"},"modified":"2012-01-08T18:21:10","modified_gmt":"2012-01-08T23:21:10","slug":"the-flyweight-pattern-misabused-at-times","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2012\/01\/08\/the-flyweight-pattern-misabused-at-times\/","title":{"rendered":"The Flyweight Pattern: (Mis|ab)used at times."},"content":{"rendered":"

In my brief career in software development thus far, I have seen a lot of “WTF” code, that is, code that deserves to be posted to The Daily WTF<\/a>. Some of this code was admittedly developed by myself and upon reviewing it a few months after it was written, I secretly wondered what I’d been thinking.<\/p>\n

This isn’t going to be an indictment of bad programming; in fact, I think it’s good if you can look back at your old code and see where it could be improved. Such a process suggests that you are continually self-improving<\/em>, a skill crucial in software development. Besides, all of us have made a mistake or two at times when we were stressed, tired or just plain not thinking straight.<\/p>\n

However, there’s one mistake that I’ve seen that I think warrants bringing to light, and that is the misuse of the Flyweight pattern<\/em>.<\/p>\n

<\/p>\n

Who wants to be a Flyweight?<\/h2>\n

Flyweight is typically used to describe one of the smaller weight classes in boxing or other fighting sports. This “minimal” aspect is what is shared with the design pattern of the same name. Simply put, a Flyweight object is one that reduces memory use by sharing common data with other objects. Despite this plain definition, implementing the Flyweight pattern can be tricky.<\/p>\n

Perhaps this is why I have seen examples like this: (Java pseudo-code below; may not compile, but you shouldn’t use it anyways<\/em>)<\/p>\n

public class WidgetWithManyFields() {\r\n  private Data field1;\r\n  private String field2;\r\n  private int field3;\r\n  \/\/ A lot more fields...\r\n  private SomeOtherData fieldN;\r\n\r\n  \/\/ Getters and setters...\r\n}<\/code><\/pre>\n

Now, obviously the memory footprint of WidgetWithManyFields<\/code> can be quite large, and since not all aspects of an application will need access to all data fields, it was decided that a “Flyweight” was needed:<\/p>\n

public class WidgetFlyweight() {\r\n  \/\/ Only these fields are needed.\r\n  private Data field1;\r\n  private String field2;\r\n\r\n  public WidgetFlyweight() {\r\n    \/\/ Default constructor.\r\n  }\r\n  \r\n  \/\/ Constructor to make one from the regular widget class.\r\n  public WidgetFlyweight(WidgetWithManyFields widget) {\r\n    this.field1 = widget.getField1();\r\n    this.field2 = widget.getField2();\r\n  }\r\n  \/\/ Getters and setters...\r\n}<\/code><\/pre>\n

This isn’t really the Flyweight pattern at all. In fact, I don’t even know if it is a pattern at all. It might be considered something like the Proxy pattern, if<\/em> the “Flyweight” class contained an instance of the regular class. But I don’t really know.<\/p>\n

So what is a Flyweight?<\/h2>\n

Consider the example of a document that can have images embedded in it. There might be multiple copies of the same image present in the document, but each copy would be sized and positioned differently within the document. <\/p>\n

In this case, you wouldn’t want to load and store the data in memory for multiple copies of the same image as that would be wasteful. However, each instance of the image displayed in the document might be formatted or positioned differently. How might this be done?<\/p>\n

Firstly, some assumptions:<\/p>\n

    \n
  • An image is uniquely identified by some resource path.<\/li>\n
  • The underlying image data does not change during the lifetime of the application.<\/li>\n<\/ul>\n

    With these assumptions, we can define three classes that allow us to implement the Flyweight pattern.<\/p>\n

    Firstly, an ImageData<\/code> class that encapsulates the actual image data. There should be only one canonical instance of this class for each unique resource path. Because of this, we can pool these objects for reuse.<\/p>\n

    However, the ImageData<\/code> objects won’t be directly used by other parts of the application. Instead, we create an ImageFlyweight<\/code> class that is manipulated. Each instance contains a reference to a canonical ImageData<\/code> object and also stores information about how to format and position the image.<\/p>\n

    In this way, there can be multiple ImageFlyweight<\/code> instances that reference the same image and hence the same ImageData<\/code> instance, but each instance would define separate formatting and positioning details.<\/p>\n

    Tying everything together is a factory (ImageFlyweightFactory<\/code>) that maintains the pool and is the access point for getting instances of ImageFlyweight<\/code>.<\/p>\n

    Below is the code: (Sorry, it’s a lot of code to throw at you at once, but I didn’t feel like breaking it down into separate chunks, and you can just copy & paste it into your favourite IDE for inspection\/compilation)<\/p>\n

    \/**\r\n * Copyright (c) 2012 Peter Chng, http:\/\/unitstep.net\/\r\n *\/\r\npackage net.unitstep.examples.flyweight;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\n\/**\r\n * In order for the Flyweight Pattern to be effective, ImageFlyweight instances\r\n * should only be obtained via ImageFlyweightFactory.getImageFlyweight().\r\n *\r\n * This ensures that for each unique resource path, there is only one instance\r\n * of the backing ImageData existing in the application.\r\n *\r\n * @author Peter Chng\r\n *\/\r\npublic class ImageFlyweightFactory {\r\n  private Map<String, ImageData> imageDataPool =\r\n      new HashMap<String, ImageData>();\r\n\r\n  public ImageFlyweight getImageFlyweight(final String resourcePath) {\r\n    \/\/ This will return a new ImageFlyweight object each time; however, the\r\n    \/\/ backing ImageData might be shared across multiple ImageFlyweight\r\n    \/\/ instances.\r\n    return new ImageFlyweight(this.getImageData(resourcePath));\r\n  }\r\n\r\n  private ImageData getImageData(final String resourcePath) {\r\n    ImageData imageData = this.imageDataPool.get(resourcePath);\r\n    if (null == imageData) {\r\n      imageData = new ImageData(resourcePath);\r\n      this.imageDataPool.put(resourcePath, imageData);\r\n    }\r\n    return imageData;\r\n  }\r\n\r\n  \/**\r\n   * @return the current count of ImageData instances in the pool; only for\r\n   *         testing purposes.\r\n   *\/\r\n  public int getImageDataPoolCount() {\r\n    return this.imageDataPool.size();\r\n  }\r\n\r\n  \/**\r\n   * Will contain the data representing an image loaded from some resource, i.e.\r\n   * the file system.\r\n   *\r\n   * This is a private inner class because it should never need to be used\r\n   * externally by callers. It is considered an implementation detail.\r\n   *\r\n   * We assume that the resource path is the uniquely-identifying aspect of an\r\n   * image and that the underlying image resource\/data will not change over the\r\n   * lifetime of the application.\r\n   *\r\n   * Thus, only one instance of the ImageData class is needed for each image\r\n   * uniquely identified by its resource path.\r\n   *\r\n   * @author Peter Chng\r\n   *\/\r\n  private class ImageData {\r\n    private final byte[] data;\r\n    private final String resourcePath;\r\n\r\n    public ImageData(final String resourcePath) {\r\n      this.resourcePath = resourcePath;\r\n\r\n      \/\/ Image data would be loaded here based on the resource path supplied.\r\n      \/\/ For brevity, it's not really done.\r\n      this.data = new byte[] {};\r\n    }\r\n\r\n    public byte[] getData() {\r\n      \/\/ Note: If we really intend to make this class immutable, we should\r\n      \/\/ return a defensive copy instead so that callers cannot modify the\r\n      \/\/ data stored in this instance.\r\n      return this.data;\r\n    }\r\n\r\n    public String getResourcePath() {\r\n      return resourcePath;\r\n    }\r\n\r\n    \/\/ Note: Not strictly necessary to override equals() and hashCode() for this\r\n    \/\/ example, but it's done to indicate we only consider the resource path\r\n    \/\/ in determining equality.\r\n    @Override\r\n    public boolean equals(final Object object) {\r\n      if (null == object) {\r\n        return false;\r\n      }\r\n      if (object == this) {\r\n        return true;\r\n      }\r\n      if (object.getClass() != this.getClass()) {\r\n        return false;\r\n      }\r\n      return this.resourcePath.equals(((ImageData) object).getResourcePath());\r\n    }\r\n\r\n    @Override\r\n    public int hashCode() {\r\n      return this.resourcePath.hashCode();\r\n    }\r\n  }\r\n\r\n  \/**\r\n   * The ImageFlyweight object contains a reference to a canonical ImageData\r\n   * object containing the actual image data we wish to render.\r\n   *\r\n   * By making this a static inner class of {@link ImageFlyweightFactory} and\r\n   * the constructor private, instantiation of this class can be controlled and\r\n   * limited to only the {@link ImageFlyweightFactory}. Callers MUST obtain an\r\n   * instance of the ImageFlyweight through the factory and not by direct\r\n   * instantiation.\r\n   *\r\n   * It also contains other properties that will affect the rendering of the\r\n   * image in the application, such as height, width and position.\r\n   *\r\n   * Reusing the same ImageData object across different ImageFlyweight instances\r\n   * allows us to display the same image in different ways within the\r\n   * application, without having to load (or store in memory) the image data\r\n   * multiple times.\r\n   *\r\n   * @author Peter Chng\r\n   *\/\r\n  public static class ImageFlyweight {\r\n    private final ImageData imageData;\r\n\r\n    private int height;\r\n    private int width;\r\n    private int positionX;\r\n    private int positionY;\r\n\r\n    private ImageFlyweight(final ImageData imageData) {\r\n      this.imageData = imageData;\r\n    }\r\n\r\n    public byte[] getData() {\r\n      return this.imageData.getData();\r\n    }\r\n\r\n    \/\/ Getters\/setters for height, width, positionX, positionY...\r\n\r\n    public int getHeight() {\r\n      return height;\r\n    }\r\n\r\n    public void setHeight(int height) {\r\n      this.height = height;\r\n    }\r\n\r\n    public int getWidth() {\r\n      return width;\r\n    }\r\n\r\n    public void setWidth(int width) {\r\n      this.width = width;\r\n    }\r\n\r\n    public int getPositionX() {\r\n      return positionX;\r\n    }\r\n\r\n    public void setPositionX(int positionX) {\r\n      this.positionX = positionX;\r\n    }\r\n\r\n    public int getPositionY() {\r\n      return positionY;\r\n    }\r\n\r\n    public void setPositionY(int positionY) {\r\n      this.positionY = positionY;\r\n    }\r\n  }\r\n}<\/code><\/pre>\n

    Everything is contained within the ImageFlyweightFactory<\/code> class, because the ImageData<\/code> class does not need to be visible to outsiders and callers should not be able to instantiate ImageFlyweight<\/code> instances on their own.<\/p>\n

    With this code, we have a simple test harness to verify whether it’s working:<\/p>\n

    \/**\r\n * Copyright (c) 2012 Peter Chng, http:\/\/unitstep.net\/\r\n *\/\r\npackage net.unitstep.examples.flyweight;\r\n\r\nimport net.unitstep.examples.flyweight.ImageFlyweightFactory.ImageFlyweight;\r\n\r\nimport org.apache.log4j.Logger;\r\n\r\n\/**\r\n * @author Peter Chng\r\n *\/\r\npublic class ImageFlyweightTest {\r\n\r\n  private static final Logger LOGGER =\r\n      Logger.getLogger(ImageFlyweightTest.class);\r\n\r\n  public static void main(final String[] args) {\r\n    final ImageFlyweightFactory factory = new ImageFlyweightFactory();\r\n\r\n    final String resourcePath1 = \"\/path\/to\/images\/someImage.png\";\r\n    final String resourcePath2 = \"\/path\/to\/images\/anotherImage.png\";\r\n\r\n    final ImageFlyweight image1 = factory.getImageFlyweight(resourcePath1);\r\n\r\n    displayImageDataCountInPool(factory);\r\n\r\n    final ImageFlyweight image2 = factory.getImageFlyweight(resourcePath2);\r\n\r\n    displayImageDataCountInPool(factory);\r\n\r\n    \/\/ Should not create an new ImageData instance in the pool.\r\n    final ImageFlyweight image3 = factory.getImageFlyweight(resourcePath1);\r\n\r\n    displayImageDataCountInPool(factory);\r\n  }\r\n\r\n  private static void displayImageDataCountInPool(\r\n      final ImageFlyweightFactory factory) {\r\n    LOGGER.debug(\"Current number of ImageData instances: \"\r\n        + factory.getImageDataPoolCount());\r\n  }\r\n}<\/code><\/pre>\n

    Running the code yields the following results:<\/p>\n

    \r\nDEBUG ImageFlyweightTest - Current number of ImageData instances: 1\r\nDEBUG ImageFlyweightTest - Current number of ImageData instances: 2\r\nDEBUG ImageFlyweightTest - Current number of ImageData instances: 2\r\n<\/pre>\n

    The key point is that after the third ImageFlyweight <\/code> object is created, the count in the ImageData<\/code> pool does not increase since the same image has already been “loaded”.<\/p>\n

    Other examples<\/h2>\n

    Note that Java itself implements something similar to the Flyweight pattern for Strings; this is known as string interning<\/em> and many other languages support this feature as well.<\/p>\n

    Basically, because Strings are immutable, Java can store each distinct value in a pool and then reuse these instances when appropriate. As an example, the following code displays “EQUAL”:<\/p>\n

    String string1 = \"A test of the string intern pool.\";\r\nString string2 = \"A test of the string intern pool.\";\r\n\/\/ Note that we are comparing object identity, NOT equality.\r\nif (string1 == string2) {\r\n  System.out.println(\"EQUAL\");\r\n} else {\r\n System.out.println(\"NOT EQUAL\");\r\n}<\/code><\/pre>\n

    Note that this doesn’t work if you directly create a String using the new<\/code> keyword.<\/p>\n

    Conclusion<\/h2>\n

    I know that this was a fairly contrived example (aren’t they all?), but I hope it provided the basics of the Flyweight pattern to readers. There are a lot of holes and I don’t suggest you directly copy this example for production code, but instead learn the skills to effectively develop the pattern on your own.<\/p>\n

    As always, I welcome questions or comments and especially corrections if I’ve made a mistake! Thanks for reading!<\/p>","protected":false},"excerpt":{"rendered":"

    In my brief career in software development thus far, I have seen a lot of “WTF” code, that is, code that deserves to be posted to The Daily WTF. Some of this code was admittedly developed by myself and upon reviewing it a few months after it was written, I secretly wondered what I’d been […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[208,197,277],"tags":[389],"_links":{"self":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/1312"}],"collection":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/comments?post=1312"}],"version-history":[{"count":23,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/1312\/revisions"}],"predecessor-version":[{"id":1348,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/1312\/revisions\/1348"}],"wp:attachment":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/media?parent=1312"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/categories?post=1312"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/tags?post=1312"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}