javadesign-patternsflyweight-pattern

Flyweight design pattern getting Object parameter as its key?


I am trying to reduce duplicates of Book objects using Flyweight design pattern but got stuck at some point.

For example, assuming that there is a book class which contains some variables such as bookName, published_date and Langauge, and someone creates a book instance:

bookName: ABC // published_date: 17-05-2020 // Langauge: English.

What I am trying to do is, when he clones the same book instance above, I want to reduce the duplicates.

But, when I searched up for the flyweight pattern, they all get String or Integer as an intrinsic value / key.

Example:

class CoffeeFlavorFactory {

  private Map<String, CoffeeFlavor> flavors = new HashMap<String, CoffeeFlavor>();
   CoffeeFlavor getCoffeeFlavor(String flavorName) {
      CoffeeFlavor flavor = flavors.get(flavorName);
      if (flavor == null) { 
          flavor = new CoffeeFlavor(flavorName);
          flavors.put(flavorName, flavor);
      }
      return flavor;
 }

The above code gets String flavorName as an intrinsic value.

What I want to ask is, is there any way to get the Book object as an intrinsic value and use the flyweight pattern?

Thanks in advance!


Solution

  • your problem doesn't sound like the intented usage scenario for the flyweight pattern which is for a big number of objects (build with repeating attributes/child objects) to "outsource" the repeatingly needed attributes/child objects to a central memory structure and then when a certain main object from your collection of objects is used to rebuild it by referencing the "outsourced" objects. (check here enter link description here
    In you example you would outsource publishDate and Language objects if they were objects.

    What I understood you want to do is simply preventing the creation of a duplicate if there already is an instance of that same book registered. The "same book" is currently identified by three attributes (bookName, bookPublishingDate, bookLanguage).

    You can do this with your approach only the key in the hashmap should be aggregated out of all relevant attributes of the book.

    Like

    String bookSignature = bookName+bookPublishingDate.toString()+bookLanguage;

    The creation of the String can be done with a StringBuilder if you want to save memory.