Flyweight, and your application will fly..

The flyweight design pattern is super simple, yet it slips out the avg’ developer mind..

It’s one of the GoF patterns, a structural one..

What is GoF?

GoF, Gang of Four, are four intelligent writers, who wrote the coolest, most popular design patterns book in the 90’s.

Most of them are now working in the IBM research department..

The book is all about OO design patterns, I personally admire them and their book, hopefully one day(soon!!) I will write my own book with a Gang of N 馃檪 wanna join?!

What is a structural design pattern?

Those are design patterns who deals with the structure of classes and the relationship between them.

The patterns make it easier for us to plan the classes and a correct form, which increase performance and scalability.

The Flyweight pattern

When we plan a class, and we are sure that there will be many instances of it in an application, we must stop and think if some of the data (variables content) will be identical for many of the instances. In that case it’s obvious that such a case will waste a lot of heap space, right?

The solution is simple, we should re factor the identical variables to an external class (Flyweight) and add a reference to it from the original class.

The most common example is a word processor: Your are in a job interview and the interviewer ask you to design a word processor, you will probably talk about a Char class, the Char class holds font, size and color variables, is that so? NO! those variables are identical for many chars that resides next to each other…the solution is to use the Flyweight pattern, all Chars in the same group of style should reference to a Flyweight object,CharLayout.

In order to reference each char to the correct CharLayout, one would use the factory pattern..

Some other examples: duplicated UI controls (buttons, icons, panels etc..), data with externic variable, Distributed tree nodes etc..

Benefits Reduce the number of objects created, decrease memory footprint and increase performance.

Advertisements