Flyweight Pattern: Exercise Solution - Possible Error

Really enjoying the design patterns courses.

As I was carefully looking at the Flyweight Pattern exercise solution, I noticed in SpreadSheet.java that all cells are initialised as follows:

  private void generateCells() {
    for (var row = 0; row < MAX_ROWS; row++)
      for (var col = 0; col < MAX_COLS; col++)
        cells[row][col] = new Cell(row, col, getDefaultContext());
  }

  private CellContext getDefaultContext() {
    // In a real app, these values should not be hardcoded here.
    // They should be read from a configuration file.
    return new CellContext("Times New Roman", 12, false);
  }

Maybe I’m missing something, but it looks like a (default) cell context object is being instantiated in memory for each cell, which is the opposite of what the rest of the flyweight pattern is all about?

You are 100% correct. That will definitely produce a distinct object for each of the cells. Fixed by having the SpreadSheet use the CellContextFactory instead of creating each CellContext directly:

  private CellContext getDefaultContext() {
    // In a real app, these values should not be hardcoded here.
    // They should be read from a configuration file.
    return contextFactory.getContext("Times New Roman", 12, false);
  }

That is not the only way to fix it, just the simplest one.