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());
}
}