Πέμπτη 27 Ιανουαρίου 2022

Flyweight pattern

  • What problem does Flyweight pattern solve?



Suppose we need to create and log Vehicle objects with random locations, at regular intervals, for an extended period

If we just create "new Vehicle().." every time, we will definitely get and OutOfMemory exception



How are we going to approach this issue?

Consider that we only need new locations. The Vehicle object instantiation is the same every time.



  • How does Flyweight pattern solve this?


We use the Factory pattern to provide the same Vehicle object to the caller, and then we can just set the random locations, and log it

Thus, our memory will now handle only 2 objects (one Truck and one Car)


This VehicleFactory has a vehicles property that holds only one instance of each vehicle type


Finally we use this factory to replace our previous "new Car()..", "new Truck()..", and set location, and log





Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

What may be missing, or could get better?