Iterator, Memento and Flyweight Patterns

Site Admin · 11 Sep 2026 · 10 views

Iterator, Memento and Flyweight Patterns

These three patterns address very different concerns but share a common goal: they hide complexity from the client code. The Iterator pattern provides a standardised way to traverse a collection without exposing its internal structure. The Memento pattern captures and restores an object's internal state. The Flyweight pattern shares common parts of similar objects to save memory.

Iterator Pattern

The Iterator defines a hasNext and next contract for traversing elements. Your collection class implements Iterable and provides an iterator method that returns an Iterator. Client code uses a simple loop without knowing whether the collection is backed by an array, a linked list, or a tree.

public interface Iterator<T> {
    boolean hasNext();
    T next();
}

public class BookShelf implements Iterable<String> {
    private String[] books;
    private int count = 0;

    public void addBook(String book) {
        books[count++] = book;
    }

    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int index = 0;
            public boolean hasNext() { return index < count; }
            public String next() { return books[index++]; }
        };
    }
}

The BookShelf hides its array internally. The iterator object walks over it one element at a time. Client code uses: for (String book : shelf) { System.out.println(book); }. If you later change the storage to a List<String>, the for-each loop stays unchanged.

Memento Pattern

The Memento pattern saves an object's internal state so it can be restored later. The originator creates a memento containing a snapshot of its fields. A caretaker stores the memento and can hand it back to the originator when an undo is needed.

public class Editor {
    private String text;

    public void setText(String text) { this.text = text; }
    public String getText() { return text; }

    public Memento save() {
        return new Memento(text);
    }

    public void restore(Memento m) {
        this.text = m.getSavedText();
    }

    public static class Memento {
        private final String text;
        Memento(String text) { this.text = text; }
        String getSavedText() { return text; }
    }
}

The Memento is a static inner class so it can access Editor's private fields. The caretaker simply stores Memento objects in a stack: stack.push(editor.save()) to save, editor.restore(stack.pop()) to undo.

Flyweight Pattern

The Flyweight shares common intrinsic state across many objects. Imagine rendering one million trees in a forest. Each tree has a unique position (extrinsic) but shares a tree type with a texture and colour (intrinsic). Creating one million texture objects wastes memory. A flyweight factory creates one texture per type and reuses it.

public class TreeType {
    private String name;
    private String color;
    private String texture;

    public TreeType(String name, String color, String texture) {
        this.name = name;
        this.color = color;
        this.texture = texture;
    }

    public void draw(int x, int y) {
        System.out.println("Draw " + name + " at (" + x + "," + y + ")");
    }
}

public class TreeTypeFactory {
    private static Map<String, TreeType> types = new HashMap<>();

    public static TreeType get(String name, String color, String texture) {
        String key = name + color + texture;
        return types.computeIfAbsent(key,
            k -> new TreeType(name, color, texture));
    }
}

The factory stores one TreeType per unique combination. Each Tree in the forest references the shared type for its visuals but holds its own x and y coordinates. Memory usage drops from one million texture objects to one.

Real-World Scenario

A text editor combines all three patterns. The Iterator walks through paragraphs for spell checking. The Memento stores snapshots for undo and redo. The Flyweight shares character glyph data across thousands of characters, each glyph storing only its shape once while individual character objects hold their position on the page.

Key Points

  • The Iterator abstracts traversal over any collection behind a hasNext and next contract.
  • The Memento captures and restores internal state without exposing implementation details.
  • The Flyweight shares intrinsic state across many objects to minimise memory usage.
  • These three patterns reduce coupling, simplify client code, and improve resource efficiency.
  • Real systems often combine them - a game engine uses iterators over entities, mementos for undo, and flyweights for shared textures.
Share this post:

Comments (0)

Please login or register to comment.