Flyweight Design Pattern

Back To Index

Overview

The Flyweight Design Pattern is used to minimize memory usage by sharing as much data as possible with other similar objects. It is especially useful when a large number of objects need to be created that share common data.

Key Characteristics

Implementation

The following is an example of a Flyweight implementation in Java:


import java.util.HashMap;
import java.util.Map;

// Flyweight interface
interface Shape {
    void draw(String color);
}

// Concrete Flyweight
class Circle implements Shape {
    private String radius;

    public Circle(String radius) {
        this.radius = radius;
    }

    @Override
    public void draw(String color) {
        System.out.println("Drawing Circle with radius " + radius + " and color " + color);
    }
}

// Flyweight Factory
class ShapeFactory {
    private static final Map shapes = new HashMap<>();

    public static Shape getCircle(String radius) {
        Shape circle = shapes.get(radius);

        if (circle == null) {
            circle = new Circle(radius);
            shapes.put(radius, circle);
            System.out.println("Creating new Circle with radius: " + radius);
        }
        return circle;
    }
}

// Demo
public class FlyweightDemo {
    public static void main(String[] args) {
        Shape circle1 = ShapeFactory.getCircle("5");
        circle1.draw("Red");

        Shape circle2 = ShapeFactory.getCircle("5");
        circle2.draw("Blue");

        Shape circle3 = ShapeFactory.getCircle("10");
        circle3.draw("Green");
    }
}
    

When to Use

Advantages

Disadvantages

Back To Index