Content What is Design Pattern What is Flyweight Design Pattern When should we use the design patterns? Types of Design Pattern Flyweight Design Pattern Advantage of Flyweight Pattern Usage of Flyweight Pattern How to Implement Example
What is Design Pattern Design Pattern is a well-proved solution for solving the specific problem/task. It is a general reusable solution to a commonly occurring problem in software design. Example.....
What is Design Pattern A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.
When should we use the design patterns? We must use the design patterns during the analysis and requirement phase of SDLC(Software Development Life Cycle).
Types of Design Pattern Creational Structural Behavioral
Flyweight Design Pattern It is a structural design Pattern Flyweight pattern is primarily used to reuse already existing similar kind of objects by storing them and create new object when no matching object is found:
Advantage of Flyweight Pattern It reduces the number of objects. It reduces the amount of memory and storage devices required if the objects are persisted
Usage of Flyweight Pattern When an application uses number of objects When the storage cost is high because of the quantity of objects. When the application does not depend on object identity.
How to Implement 1.Divide fields of a class that will become a flyweight into two parts: T he intrinsic state: the fields that contain unchanging data duplicated across many objects T he extrinsic state: the fields that contain contextual data unique to each object
How to Implement 2. Leave the fields that represent the intrinsic state in the class 3. Go over methods that use fields of the extrinsic state. For each field used in the method, introduce a new parameter and use it instead of the field.
Real world example of flyweight pattern Suppose we have a pen which can exist with/without refill. A refill can be of any color thus a pen can be used to create drawings having N number of colors. Here Pen can be flyweight object with refill as extrinsic attribute. All other attributes such as pen body, pointer etc. can be intrinsic attributes which will be common to all pens. A pen will be distinguished by its refill color only, nothing else.
Real world example of flyweight pattern All application modules which need to access a red pen – can use the same instance of red pen (shared object). Only when a different color pen is needed, application module will ask for another pen from flyweight factory.