0

最近学习了享元模式,其中一个概念就是内存缓存。但是,在阅读了一些文章之后,我仍然不明白。

在本教程中,它使用地图作为一个简单的缓存,但为什么地图有这种属性呢?有没有清晰简单的解释? https://www.baeldung.com/java-flyweight

我参考了java文档:https ://docs.oracle.com/cd/B14099_19/web.1012/b14012/objcache.htm

教程中的插图是不完整的,所以我写了关于它的代码。

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

这是我的主要方法

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

0 回答 0