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

What's hot (20)

React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Composite design pattern
Composite design patternComposite design pattern
Composite design pattern
 
Asp objects
Asp objectsAsp objects
Asp objects
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Strategy Pattern
Strategy PatternStrategy Pattern
Strategy Pattern
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Spring annotations notes
Spring annotations notesSpring annotations notes
Spring annotations notes
 
Jpa
JpaJpa
Jpa
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 

Similar to Flyweight Design Pattern

The Joy of ServerSide Swift Development
The Joy  of ServerSide Swift DevelopmentThe Joy  of ServerSide Swift Development
The Joy of ServerSide Swift DevelopmentGiordano Scalzo
 
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 DevelopmentGiordano Scalzo
 
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 DevelopmentGiordano Scalzo
 
Writing good code
Writing good codeWriting good code
Writing good codeIshti Gupta
 
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 2009Heiko Behrens
 
Haxe for Flash Platform developer
Haxe for Flash Platform developerHaxe for Flash Platform developer
Haxe for Flash Platform developermatterhaxe
 
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 curseYonatan Levin
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseYonatan Levin
 
Restful Web Service
Restful Web ServiceRestful Web Service
Restful Web ServiceBin Cai
 
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 stackBram Vogelaar
 
Kotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesKotlin from-scratch 3 - coroutines
Kotlin from-scratch 3 - coroutinesFranco Lombardo
 
Node.js - Advanced Basics
Node.js - Advanced BasicsNode.js - Advanced Basics
Node.js - Advanced BasicsDoug Jones
 
Dart, unicorns and rainbows
Dart, unicorns and rainbowsDart, unicorns and rainbows
Dart, unicorns and rainbowschrisbuckett
 
There's more than web
There's more than webThere's more than web
There's more than webMatt 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

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Recently uploaded (20)

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

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