What is the difference between Builder Pattern and Flyweight Pattern in terms of usage, as both of them deals with large number of objects?
The Builder pattern is used to create many objects, whereby the Flyweight pattern is about sharing such a collection of objects.
These two patterns both deal with "composites", i.e. objects that may have several elements, but they don't need to be used together at all. The archetype use case for Flyweight is where a pool of a few dozen characters objects are used over and over in a text editor application (this is the example given in the "GoF" book)
Straight from wikipedia.
Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
The Builder Pattern is a software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects.
One helps with building objects and the other help with memory usage. You could potentially use a builder to "Build" different flyweight objects.
flyweight pattern is appropriate when "many objects must be manipulated and these cannot afford to have extraneous data." In Java, String objects are managed as flyweight. Java puts all fixed String literals into a literal pool. For redundant literals, Java keeps only one copy in the pool.
The key to making flyweight work is by controlling object instantiation using a factory method or builder design pattern. The job of a factory method is simply to create objects: given input criteria, return an object of appropriate type.
Abstract factory is similar to builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract factor's emphasis is on families of product objects(either simple or complex).
© 2022 - 2024 — McMap. All rights reserved.