0

I learned the flyweight pattern recently, and one of the concepts is memory caching. However, after reading some articles, I still don't get the idea.

In this tutorial, it uses the map as a simple cache, but why the map has this kind of property? Is there any clear and simple explanation? https://www.baeldung.com/java-flyweight

I've referred to the java doc: https://docs.oracle.com/cd/B14099_19/web.1012/b14012/objcache.htm

The illustration in the tutorial is incomplete, so I wrote the code about it.

class Car implements Vehicle
{
private Engine engine; // another class
private Color color; // enum

private Car(Engine engine, Color color)
{
    this.engine = engine;
    this.color = color;
}

public void start()
{
    System.out.println("The engine started.");
}

public void stop()
{
    System.out.println("The engine stopped");
}

public Color getColor()
{
    return color;
}
// the author mentioned the memory cache using the map in the Factory method
static class VehicleFactory
{
    private Map<Color, Vehicle> vehiclesCache
  = new HashMap<>();
 
    public Vehicle createVehicle(Color color) {
    Vehicle newVehicle = vehiclesCache.computeIfAbsent(color, newColor -> { 
        Engine newEngine = new Engine();
        return new Car(newEngine, newColor);
    });
    return newVehicle;
    }
}

@Override
public String toString()
{
    return "The color of the car: " + getColor().toString().toLowerCase() +
           ", and the engine is from: " + engine.toString();
}
}

And here is my main method

class FlyWeight
{
public static void main(String [] args)
{
    Car.VehicleFactory carFactory = new Car.VehicleFactory();
    Car car = (Car) carFactory.createVehicle(Color.BLACK);

    System.out.println(car.toString());
}
}
Woden
  • 1,054
  • 2
  • 13
  • 26
  • 2
    Which part don't you understand? "Building a new vehicle is a very expensive operation so the factory will only create one vehicle per color." - that's why `Color` is the map key to easily verify if the object already exists and return if it it does. – Amongalen Jul 07 '20 at 13:31
  • 1
    You can check this too https://www.journaldev.com/1562/flyweight-design-pattern-java – Harmandeep Singh Kalsi Jul 07 '20 at 13:35
  • Thank you @Amongalen. After your explanation, now I understand. – Woden Jul 07 '20 at 14:06
  • @HarmandeepSinghKalsi thank you, I'll read it. – Woden Jul 07 '20 at 14:06

0 Answers0