Flyweight Design Pattern in Java

Flyweight Pattern is a structural pattern as it is used to form large object structures across many disparate objects. This pattern minimizes memory use by sharing as much data as possible with other similar objects. This pattern increases performance by avoid creating a large number of expensive objects and instead reusing the existing instances to represent new ones.

Class Diagram

Flyweight Pattern in Java

Implementation

We first create a class, IcecreamFlavour, which represents different flavours of icecream.

Next we create a class called IcecreamMenu which is having lookup method that creates a new icecream flavour if a flavour does not already exist and returns the icecream flavour.

Now we have below class to track orders

Using the below class we will serve the icecream of different flavours

Run the above class and see the output as shown below

Output

That’s all. Thanks for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.