Why is the (GoF) Flyweight a structural (and not a creational) design pattern?
Asked Answered
M

2

10

To my understanding, the flyweight design pattern is not so different from the factory or singleton design patterns.

It is just a factory that produces immutable (and pooled) objects. It is just a singleton that provides one instance per type (of the managed objects), instead of a global single instance.

Factory and singleton are creational patterns, so why should the flyweight be considered a structural pattern?

Margalo answered 9/6, 2015 at 23:1 Comment(1)
On the one hand, the classifications of patterns is not so important and might appear arbitrary at first in some cases. On the other hand, I disagree with saying it's just a factory that produces immutable objects. Abstract Factory and Factory Method in GoF have much more context. Lots of people confuse Simple Factory and Factory Method.Kanzu
H
4

The essence of the Flyweight pattern is not creation of objects but sharing of them. The pattern states that the objects to be shared are usually held in some external data structure but does not specify how those data structures are created or represented.

What makes the pattern structural is the use of factory-like class to obtain the flyweights. This imposes a static structure on the design.

Horse answered 10/6, 2015 at 14:5 Comment(0)
O
1

The flyweight pattern doesn't create any objects. It used to store data shared among multiple objects. You can compare its use with static methods/variables in a class. Instead of defining them for each instance you can use a global instance that holds this method or data to reduce the memory footprint of your application.

Suppose you're parsing a large data file using multiple parsers, instead of having each parser read the complete data file, you could use the flyweight pattern to hold a single instance of the data file which each parser can access.

Operable answered 10/6, 2015 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.