The flyweight pattern is used for memory optimization purposes, the design pattern is usually chosen
whenever there is a need to reduce the number of created objects.
The reason why this pattern has been included in a structural pattern is categories because it is used
to optimize the object structures by reducing the memory footprint of your program through creating
a smaller number of objects.
The scope of it is to revitalize the already created objects and to avoid creating new instances whenever
an object is needed in our code.
We will have an online store composed of a backend application and a client application.
The backend application consists of the inventory back, an object which is used to process the order
sent by the client application.
The orders are created on the market object and the orders contain different products.
The product object is our flyweight object, therefore we will demonstrate that whenever two orders
are created on the same product, only one instance of that product will be created by our application.
Therefore, reducing the memory usage of the program.
As a general rule, this pattern is suitable only for stateless or immutable objects.
The definition for an immutable object is whenever an object cannot be changed after its creation.
Such an example is the string object from the job IEEPA.
Some of the biggest weaknesses of this pattern is that it can become a bit too complex, being more
of an optimization solution for issues related to memory management.
Let's have a look at the implementation of this pattern in the code.