SlideShare a Scribd company logo
1 of 20
Flyweight
A STRUCTURAL DESIGN PATTERN


                              Amit B Jambusaria
                              Varun M Chidananda

                              Syracuse University
Agenda

    Motivation
    Topic Introduction
    Structure of the Flyweight
    Real World Examples
    Code walk through
    Demo
    Summary
Motivation




             Looks alright, right?
Introduction
    Designing objects down to the lowest levels of system granularity
     provides optimal flexibility, but can be unacceptably expensive in
     terms of performance and memory usage.


    The Flyweight Pattern is a pattern for greatly reducing memory
     requirements.


    The flyweight pattern applies to a program using a huge number of
     objects that have part of their internal state in common where the
     other part of state can vary.


    The idea behind flyweight pattern is shareable objects.
Structure of the Flyweight
   It can be confusing at first to understand how the flyweight
     pattern works. Let’s first take a high-level look at the structure.
                                                                                        SUID

   Each object is divided into two pieces:
                                                                                     First Name




                                                                           student
     -- the state-independent (intrinsic) part
     -- and the state-dependent (extrinsic) part
                                                                                     Last Name

   Intrinsic state is stored (shared) in the Flyweight object.                      Department

   Extrinsic state is stored or computed by client objects, and                      University
                                                                                       Name
    passed to the Flyweight when its operations are invoked.
Real World Example
Word Processor
    A classic example usage of the flyweight pattern is the data structures
     for graphical representation of characters in a word processor.


    The term flyweight pattern was first coined and extensively explored
     by Paul Calder and Mark Linton in 1990 to efficiently handle glyph
     information in a WYSIWYG document editor.


    For each character in a document, we can create a glyph object
     containing information such as the font family, size, weight of each
     character and other formatting data.


    The problem here is that a lengthy document might contain tens of
     thousands of characters and corresponding objects - quite a memory
     killer !!!
   The Flyweight pattern addresses the problem by creating a new object
    to store such information, which is shared by all characters with the
    same formatting.


   The intrinsic state here could be the shared information such as font-
    family, font-size, font weight and so one.


   The extrinsic state would be the information that distinguishes each
    physical character such as row information or the x-y co-ordinate of the
    character.


   So, if I had a ten-thousand word document, with 800 characters in Bold
    Times-New-Roman size-14pt, these 800 characters would contain a
    reference to a flyweight object that stores their common formatting
    information.


   The key here is that you only store the information once, so memory
    consumption is greatly reduced.
Aircraft Example
   Lets suppose we have to model some complex aircrafts such
    as Airbus 380 and Boeing 797
Aircraft              Flyweight Object


           Wingspan                      Wingspan



            Speed                         Speed



           Capacity                      Capacity


            Serial
           Number


             Date
            bought
public class Boeing797
                                     public class Airbus380 ::public IModel
                                                               public IModel

                                     {
                                         private:
                                      private:
                                             std::string name;
                                           std::string name;
public class IModel                             std::string wingspan;
                                               std::string wingspan;
                                                int capacity;
                                               int capacity;
{                                               std::string speed;
                                               std::string speed;
                                               std::string range;
private:                                       std::string range;

                                     public:
    std::string name;                          public: Airbus380()
                                           Boeing797 ()
                                               {
                                           {
    std::string wingspan;                             name = "AirBus380";
                                                   name = "Boeing797";
                                                      wingspan = "80.8 meters";
    int capacity;                                  wingspan = "79.8 meters";
                                                      capacity = 1000;
                                                   capacity = 555;
    std::string speed;                                speed = "1046 km per hr";
                                                   speed = "912 km per hr";
                                                      range = "14400 km";
                                                   range = "10370 km";
    std::string range;                         }
                                           }

                                         void print ()
                                               void print ()
                                           {
                                               {
public: virtual void print () = 0;             cout << "Name : " << name << "n";
                                                   cout << "Name : " << name << "n";
                                               cout << "Wingspan : " << wingspan << "n";
};                                                 cout << "Wingspan : " << wingspan << "n";
                                               cout << "Capacity : " << capacity << "n";
                                                cout << "Capacity : " << capacity << "n";
                                               cout << "Speed :: "" << speed << "n";
                                                cout << "Speed       << speed << "n";
                                           }}

                                     };
                                     };
public class FlyweightFactory        {    public class Aircraft {
 private:                                  private:
                                              IModel *_type;
     static Airbus380 *a;
                                              int _serialNo;
     static Boeing797 *b;                     std::string _dateBought;

                                          public:
 public:
                                             Aircraft (IModel *type, int serialNo,
 static IModel * GetObj (int typeNo) {       std::string dateBought)
     if (typeNo == 380) {                    {
                                                 _type = type ;
         if(a == NULL)
                                                 _serialNo = serialNo ;
             a = new Airbus380();                _dateBought = dateBought ;
         return a;                           }
     }
                                              void print()
     else   {        //if typeNo is 797       {
         if(b == NULL)                            _type->print();
                                                  cout << "Serial No : " << _serialNo <<
             b = new Boeing797();
                                          "n";
         return b;                                cout << "Date Bought : " <<
     }                                    _dateBought << "n";
                                                  cout << endl ;
 }
                                            }
};                                        };
// Global Static object pointer
Airbus380 * FlyweightFactory::a;
Boeing797 * FlyweightFactory::b;


// Client:
void main()
{
    Aircraft one = Aircraft( FlyweightFactory::GetObj(380) , 1001,"9th feb 2011");
    Aircraft two = Aircraft( FlyweightFactory::GetObj(380) , 1002, "11th sept 2011");
    Aircraft three = Aircraft( FlyweightFactory::GetObj(797) , 1003, "12th oct 2011");
    Aircraft four = Aircraft( FlyweightFactory::GetObj(797) , 1004, "13th dec 2011");


    one.print();
    two.print();
    three.print();
    four.print();
}
Dialog box example




Common Objects like Icons and Buttons can be shared among Dialog box classes.
Design of Dialog class with Flyweight Design Pattern
Client:
                    FileSelection

                 Go
                                 Select

                      Stop

          Go


                   Stop          Select
          Undo


                  Select         Stop


                          Undo

                 CommitTransaction
Flyweight Factory:
Code Walk Through
& Demo
Summary
• “Flyweights” Lose Equality, Gain Identity
   • Same Instance used Many Places

• “Flyweights” Must Separate Intrinsic/Extrinsic

• “Flyweights” Save Space
   • More “Flyweights” Shared Yields More Savings
   • More Intrinsic State Yields More Savings

• “Flyweights” Are Found, Not Instantiated
   • Slight Shift in Terminology

• “Flyweights” May Introduce CPU Costs
   • Finding “Flyweights” (Large Pool Increases)
Questions?




             Thank You

More Related Content

What's hot

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 

What's hot (20)

Java 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambda
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
POO - 11 - Prática de Herança
POO - 11 - Prática de HerançaPOO - 11 - Prática de Herança
POO - 11 - Prática de Herança
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Java beans
Java beansJava beans
Java beans
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
POO - Aula 09 - Herança
POO - Aula 09 - HerançaPOO - Aula 09 - Herança
POO - Aula 09 - Herança
 
Java rmi
Java rmiJava rmi
Java rmi
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Struts
StrutsStruts
Struts
 
Java RMI Presentation
Java RMI PresentationJava RMI Presentation
Java RMI Presentation
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Facade Pattern
Facade PatternFacade Pattern
Facade Pattern
 

Similar to Flyweight Design Pattern

Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
Yonatan Levin
 
Bootstrap your Cloud Infrastructure using puppet and hashicorp stack
Bootstrap your Cloud Infrastructure using puppet and hashicorp stackBootstrap your Cloud Infrastructure using puppet and hashicorp stack
Bootstrap your Cloud Infrastructure using puppet and hashicorp stack
Bram Vogelaar
 
There's more than web
There's more than webThere's more than web
There's more than web
Matt Evans
 

Similar to Flyweight Design Pattern (20)

The Joy of ServerSide Swift Development
The Joy  of ServerSide Swift DevelopmentThe Joy  of ServerSide Swift Development
The Joy of ServerSide Swift Development
 
The Joy of Server Side Swift Development
The Joy  of Server Side Swift DevelopmentThe Joy  of Server Side Swift Development
The Joy of Server Side Swift Development
 
The Joy Of Server Side Swift Development
The Joy Of Server Side Swift DevelopmentThe Joy Of Server Side Swift Development
The Joy Of Server Side Swift Development
 
Writing good code
Writing good codeWriting good code
Writing good code
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Haxe for Flash Platform developer
Haxe for Flash Platform developerHaxe for Flash Platform developer
Haxe for Flash Platform developer
 
IPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseIPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curse
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
Unit v
Unit vUnit v
Unit v
 
Restful Web Service
Restful Web ServiceRestful Web Service
Restful Web Service
 
Bootstrap your Cloud Infrastructure using puppet and hashicorp stack
Bootstrap your Cloud Infrastructure using puppet and hashicorp stackBootstrap your Cloud Infrastructure using puppet and hashicorp stack
Bootstrap your Cloud Infrastructure using puppet and hashicorp stack
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutines
 
Node.js - Advanced Basics
Node.js - Advanced BasicsNode.js - Advanced Basics
Node.js - Advanced Basics
 
Dart, unicorns and rainbows
Dart, unicorns and rainbowsDart, unicorns and rainbows
Dart, unicorns and rainbows
 
Day 1
Day 1Day 1
Day 1
 
20190705 py data_paris_meetup
20190705 py data_paris_meetup20190705 py data_paris_meetup
20190705 py data_paris_meetup
 
There's more than web
There's more than webThere's more than web
There's more than web
 
Avro
AvroAvro
Avro
 

Recently uploaded

QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 

Flyweight Design Pattern

  • 1. Flyweight A STRUCTURAL DESIGN PATTERN Amit B Jambusaria Varun M Chidananda Syracuse University
  • 2. Agenda  Motivation  Topic Introduction  Structure of the Flyweight  Real World Examples  Code walk through  Demo  Summary
  • 3. Motivation Looks alright, right?
  • 4. Introduction  Designing objects down to the lowest levels of system granularity provides optimal flexibility, but can be unacceptably expensive in terms of performance and memory usage.  The Flyweight Pattern is a pattern for greatly reducing memory requirements.  The flyweight pattern applies to a program using a huge number of objects that have part of their internal state in common where the other part of state can vary.  The idea behind flyweight pattern is shareable objects.
  • 5. Structure of the Flyweight  It can be confusing at first to understand how the flyweight pattern works. Let’s first take a high-level look at the structure. SUID  Each object is divided into two pieces: First Name student -- the state-independent (intrinsic) part -- and the state-dependent (extrinsic) part Last Name  Intrinsic state is stored (shared) in the Flyweight object. Department  Extrinsic state is stored or computed by client objects, and University Name passed to the Flyweight when its operations are invoked.
  • 7. Word Processor  A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor.  The term flyweight pattern was first coined and extensively explored by Paul Calder and Mark Linton in 1990 to efficiently handle glyph information in a WYSIWYG document editor.  For each character in a document, we can create a glyph object containing information such as the font family, size, weight of each character and other formatting data.  The problem here is that a lengthy document might contain tens of thousands of characters and corresponding objects - quite a memory killer !!!
  • 8. The Flyweight pattern addresses the problem by creating a new object to store such information, which is shared by all characters with the same formatting.  The intrinsic state here could be the shared information such as font- family, font-size, font weight and so one.  The extrinsic state would be the information that distinguishes each physical character such as row information or the x-y co-ordinate of the character.  So, if I had a ten-thousand word document, with 800 characters in Bold Times-New-Roman size-14pt, these 800 characters would contain a reference to a flyweight object that stores their common formatting information.  The key here is that you only store the information once, so memory consumption is greatly reduced.
  • 9. Aircraft Example  Lets suppose we have to model some complex aircrafts such as Airbus 380 and Boeing 797
  • 10. Aircraft Flyweight Object Wingspan Wingspan Speed Speed Capacity Capacity Serial Number Date bought
  • 11. public class Boeing797 public class Airbus380 ::public IModel public IModel { private: private: std::string name; std::string name; public class IModel std::string wingspan; std::string wingspan; int capacity; int capacity; { std::string speed; std::string speed; std::string range; private: std::string range; public: std::string name; public: Airbus380() Boeing797 () { { std::string wingspan; name = "AirBus380"; name = "Boeing797"; wingspan = "80.8 meters"; int capacity; wingspan = "79.8 meters"; capacity = 1000; capacity = 555; std::string speed; speed = "1046 km per hr"; speed = "912 km per hr"; range = "14400 km"; range = "10370 km"; std::string range; } } void print () void print () { { public: virtual void print () = 0; cout << "Name : " << name << "n"; cout << "Name : " << name << "n"; cout << "Wingspan : " << wingspan << "n"; }; cout << "Wingspan : " << wingspan << "n"; cout << "Capacity : " << capacity << "n"; cout << "Capacity : " << capacity << "n"; cout << "Speed :: "" << speed << "n"; cout << "Speed << speed << "n"; }} }; };
  • 12. public class FlyweightFactory { public class Aircraft { private: private: IModel *_type; static Airbus380 *a; int _serialNo; static Boeing797 *b; std::string _dateBought; public: public: Aircraft (IModel *type, int serialNo, static IModel * GetObj (int typeNo) { std::string dateBought) if (typeNo == 380) { { _type = type ; if(a == NULL) _serialNo = serialNo ; a = new Airbus380(); _dateBought = dateBought ; return a; } } void print() else { //if typeNo is 797 { if(b == NULL) _type->print(); cout << "Serial No : " << _serialNo << b = new Boeing797(); "n"; return b; cout << "Date Bought : " << } _dateBought << "n"; cout << endl ; } } }; };
  • 13. // Global Static object pointer Airbus380 * FlyweightFactory::a; Boeing797 * FlyweightFactory::b; // Client: void main() { Aircraft one = Aircraft( FlyweightFactory::GetObj(380) , 1001,"9th feb 2011"); Aircraft two = Aircraft( FlyweightFactory::GetObj(380) , 1002, "11th sept 2011"); Aircraft three = Aircraft( FlyweightFactory::GetObj(797) , 1003, "12th oct 2011"); Aircraft four = Aircraft( FlyweightFactory::GetObj(797) , 1004, "13th dec 2011"); one.print(); two.print(); three.print(); four.print(); }
  • 14. Dialog box example Common Objects like Icons and Buttons can be shared among Dialog box classes.
  • 15. Design of Dialog class with Flyweight Design Pattern
  • 16. Client: FileSelection Go Select Stop Go Stop Select Undo Select Stop Undo CommitTransaction
  • 19. Summary • “Flyweights” Lose Equality, Gain Identity • Same Instance used Many Places • “Flyweights” Must Separate Intrinsic/Extrinsic • “Flyweights” Save Space • More “Flyweights” Shared Yields More Savings • More Intrinsic State Yields More Savings • “Flyweights” Are Found, Not Instantiated • Slight Shift in Terminology • “Flyweights” May Introduce CPU Costs • Finding “Flyweights” (Large Pool Increases)
  • 20. Questions? Thank You