mercredi 27 mai 2020

Appropriate datastructure for flyweight

I am trying to apply the flyweight pattern in a program that generates clouds. I have a class that represents intrinsic states of clouds. A cloud type is defined by its attributes :

class CloudType {
    float size;
    float altitude;
    String color;
    String texture;

   public void display(x, y) {}

}

class ConcreteCloud {
    float x;
    float y;
    CloudType cloudType;

    void display() {
        cloudeType.display(x, y);
    }
}

I would like to create a CloudType factory that takes these characteristics as arguments and returns the corresponding instance of CloudType if it exists, else create and store it beforehand.

class CloudTypeFactory {
    //  SomeContainer<CloudType> container;

    public CloudType getCloudType(float size, float altitude, String color, String texture) {
        CloudType instance = // container get corresponding cloudType
        if (instance == null) {
            instance = new CloudeType(size, altitude, color, texture);
            container.add(instance);
        }
        return instance;
    }

}

The problem:

I have doubts concerning which container to use and consequently the architecture itself. A HashSet could be used, but the search complexity gets proportional to the number of attributes in CloudType , which doesn't seem right. In examples I read online, authors use a HashMap with the key being the name of the CloudType: this defeats the purpose IMO as there might be an infinite number of cloud types in this case.

Aucun commentaire:

Enregistrer un commentaire