SlideShare a Scribd company logo
1 of 21
Flyweight Pattern

     Structural Pattern
Motivation
       You want to draw a forest of trees!
       How would you implement this?
       Millions of tree objects in the program?
           Memory constraint
       What is the optimal solution?
       Can we implement it so that we create only 1 tree
        object?




    2
Flyweight Pattern
       That’s where flyweight comes in!
           If the objects you create have so much common
            properties (like trees, only positions are different).
       The activity diagram may be like this with only one
        instance.




       Then, we have to store positions somewhere!
           Client can do this for us.
    3
Definition
       Flyweight pattern is a pattern for sharing objects,
        where each instance does not contain its own
        state but stores it externally.
       This allows efficient sharing of objects to save
        space when there are many instances but only a
        few different types.




    4
Text Document Example
       You want to hold a text document with so many
        customizations as style.
       Each letter in with a different object?
       Creating the letter ‘E’, may be already there before,
        but with a different style!

       So we will have a
        CharFactory to return
        us the already created
        instance OR creates
        it from scratch!

    5
Structure




6
Participants
       Flyweight
           Letter as an abstract class
       SharedConcreteFlyweight
           LetterA
       UnsharedConcreteFlyweight
           Not all flyweights must be shared!
           Row information for example
       FlyweightFactory
           Creates and manages flyweights (Character factory)
       Client
           The styles are stored here, also call to factory

    7
Intrinsic & Extrinsic States
       From course slides (7.Quality of Design)
       B is extrinsic to A if A can be fully defined with no
        notion of B
           E.g., class Dog is extrinsic to class Person
       B is intrinsic to A if B captures some characteristics
        inherent to A
           E.g., class Date is intrinsic to class Person (by date of
            birth)
       What is with us?
           Extrinsic states may be stored in client!
           Intrinsic states may be stored in flyweight itself!

    8
Sequence Diagram




9
Applicability
    Use flyweight pattern iff:
        You will use large number of objects.
        You want to reduce storage costs.
        Most of object states can be extrinsic.
        Many group of objects > Fewer shared objects with states
        App doesnot care object identity.

        Ex: Drawing lots of circles
         with different colors and sizes




    10
Consequences
    Run time costs
        Client is responsible for extrinsic states (storing, fetching
         etc)
        Normally they are part of the object.
    Space saving
        Will increase as more flyweights are shared.
        How much you share, that much you save space!
    Factory
        Flyweight must be created only via factory!




    11
Demo
    Circle Drawing. (ref at the end)
    We want to draw10000 circles in 6 different colors.
    Circles have color in common. (intrinsic state)
    Position and radius information is given as extrinsic
     state. (randomly generated)




    12
Implementation Issues
    Storing extrinsic states can be tricky
        An object structure for extrinsic states
        In text document example, you can store a map of typographic
         information in seperate structure, instead of storing the font and
         style information with each object.
        This map can keep track of numbers of characters with same
         attribute.
    Accessing a specific object
        We have to design the system
         according to that need.
        In drawing tree example,
         we just draw and go.
        We can make the access
         with a pointer.

    13
Implementation Issues
    Extrinsic states can be stored but what about we
     want to change the intrinsic state of a flyweight?
        Modify the factory as to create new flyweights with a
         different intrinsic state also.
        Not so efficient, slowly breaking the flyweight pattern.
    UnsharedConcreteFlyweight is normally a totally
     different object but we can also make them sharable
     via factory.
        If they become sharable later, the oldly created ones
         should be added to factory.



    14
Relation with Other Patterns
    You can combine Composite pattern with Flyweight.
    Each UnsharedConcreteFlyweight may be
     component with SharedConcreteFlyweights as
     children.



    In text document:
     Rows are components
     or UnsharedConcFly.
     Letters are leafs
     or SharedConcFly.

    15
Relation with Other Patterns – cont’d
    FlyweightFactory produces flyweights as in Factory
     Method.
        No abstract Creator (but we can)
        FlyweightFactory is the ConcreteCreator.
        Flyweight is Product.
        Subclasses of Flyweight is ConcreteProducts.




    It only looks for an already created instance instead of
     returning new ConcreteProduct() immediately.
    16
Relation with Other Patterns – cont’d
    In State Pattern, you can share states with Flyweight
     Pattern.
        Flyweight is State.
        SharedConcreteFlyweight is ConcreteState.
        Client is Context.
    With that way, Context can share states if the state is
     already created.
        Handle method may
         also get extrinsic
         state as parameter.



    17
Relation with Other Patterns – cont’d
    The same logic works with the Strategy Pattern.
        Strategy can be shared, and algorithm can be run with
         only different inputs (extrinsic state).
        The algorithm itself is the intrinsic state.
    Difference is: flyweights can be used in many context
     but strategy is in one context.




    18
Practical Example
    Strings in Java language.




    If you don’t explicitly construct a string and put the
     value with assignment operator, they will be same.
    Actually Java has another method called intern for
     sharing strings.



    19
Thanks




         Questions?

20
References
    GoF Design Patterns Book
    Definition from: C# design patterns, James cooper
    http://www.dofactory.com/Patterns/PatternFlyweight.
     aspx#_self1
    http://fc07.deviantart.net/fs32/f/2008/218/8/7/Pine_fo
     rest_by_softwalls.jpg
    Oreilly Head First: Design Patterns Book
    Fry of Futurama for Questions Picture
    Demo:
     http://www.javacamp.org/designPattern/flyweight.htm
     l
    http://javatechniques.com/public/java/docs/basics/stri
     ng-equality.html
    21

More Related Content

What's hot

Fly Weight Design Pattern.pptx
Fly Weight Design Pattern.pptxFly Weight Design Pattern.pptx
Fly Weight Design Pattern.pptxSaifullah568810
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design PatternAdeel Riaz
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design PatternAdeel Riaz
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVCEmad Alashi
 
Getting Started with React.js
Getting Started with React.jsGetting Started with React.js
Getting Started with React.jsSmile Gupta
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Patternguy_davis
 
ג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונות
ג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונותג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונות
ג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונותמורן אלקובי
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Patternsahilrk911
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questionsjinaldesailive
 

What's hot (20)

Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Proxy design pattern
Proxy design patternProxy design pattern
Proxy design pattern
 
Fly Weight Design Pattern.pptx
Fly Weight Design Pattern.pptxFly Weight Design Pattern.pptx
Fly Weight Design Pattern.pptx
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Decorator Design Pattern
Decorator Design PatternDecorator Design Pattern
Decorator Design Pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Memento pattern
Memento patternMemento pattern
Memento pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
Getting Started with React.js
Getting Started with React.jsGetting Started with React.js
Getting Started with React.js
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
ג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונות
ג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונותג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונות
ג'אווה - תכנות מונחה עצמים - מתודות - דריסה/חפיפה, העמסה ומתודות בונות
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
 

Viewers also liked

Flyweight Design Pattern
Flyweight Design PatternFlyweight Design Pattern
Flyweight Design PatternVarun MC
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Patterneprafulla
 
Research on Stability of Software Structure Based On Design Patterns
Research on Stability of Software Structure Based On Design PatternsResearch on Stability of Software Structure Based On Design Patterns
Research on Stability of Software Structure Based On Design PatternsIJRES Journal
 
Sustainability Drinks #20 – Will Veganism Save the World? - Lisa Hapke
Sustainability Drinks #20 – Will Veganism Save the World? - Lisa HapkeSustainability Drinks #20 – Will Veganism Save the World? - Lisa Hapke
Sustainability Drinks #20 – Will Veganism Save the World? - Lisa HapkeGreenBuzz Berlin
 
31 interesting ways to use audio in your class
31 interesting ways to use audio in your class31 interesting ways to use audio in your class
31 interesting ways to use audio in your classmrholdsworth
 
Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented ParadigmHüseyin Ergin
 
Skin stringers-in-an-aircraft
Skin stringers-in-an-aircraftSkin stringers-in-an-aircraft
Skin stringers-in-an-aircraftsubhan90
 
JETPACK Scenario Planning Module
JETPACK Scenario Planning ModuleJETPACK Scenario Planning Module
JETPACK Scenario Planning ModuleCaleb Sexton
 
best ppt on jet engines
best ppt on jet enginesbest ppt on jet engines
best ppt on jet enginesDeepak Kumar
 
Subsonic and supersonic air intakes
Subsonic and supersonic air intakesSubsonic and supersonic air intakes
Subsonic and supersonic air intakesSanjay Singh
 
Basic aircraft structure
Basic aircraft structureBasic aircraft structure
Basic aircraft structurenyinyilay
 

Viewers also liked (12)

Flyweight Design Pattern
Flyweight Design PatternFlyweight Design Pattern
Flyweight Design Pattern
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Pattern
 
Research on Stability of Software Structure Based On Design Patterns
Research on Stability of Software Structure Based On Design PatternsResearch on Stability of Software Structure Based On Design Patterns
Research on Stability of Software Structure Based On Design Patterns
 
Sustainability Drinks #20 – Will Veganism Save the World? - Lisa Hapke
Sustainability Drinks #20 – Will Veganism Save the World? - Lisa HapkeSustainability Drinks #20 – Will Veganism Save the World? - Lisa Hapke
Sustainability Drinks #20 – Will Veganism Save the World? - Lisa Hapke
 
Chassisand frame
Chassisand frameChassisand frame
Chassisand frame
 
31 interesting ways to use audio in your class
31 interesting ways to use audio in your class31 interesting ways to use audio in your class
31 interesting ways to use audio in your class
 
Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented Paradigm
 
Skin stringers-in-an-aircraft
Skin stringers-in-an-aircraftSkin stringers-in-an-aircraft
Skin stringers-in-an-aircraft
 
JETPACK Scenario Planning Module
JETPACK Scenario Planning ModuleJETPACK Scenario Planning Module
JETPACK Scenario Planning Module
 
best ppt on jet engines
best ppt on jet enginesbest ppt on jet engines
best ppt on jet engines
 
Subsonic and supersonic air intakes
Subsonic and supersonic air intakesSubsonic and supersonic air intakes
Subsonic and supersonic air intakes
 
Basic aircraft structure
Basic aircraft structureBasic aircraft structure
Basic aircraft structure
 

Similar to Flyweight Pattern Explained for Memory Optimization

Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Scriptable Objects in Unity Game Engine (C#)
Scriptable Objects in Unity Game Engine (C#)Scriptable Objects in Unity Game Engine (C#)
Scriptable Objects in Unity Game Engine (C#)Om Shridhar
 
Java OOPs Concepts.docx
Java OOPs Concepts.docxJava OOPs Concepts.docx
Java OOPs Concepts.docxFredWauyo
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesBalamuruganV28
 
M.c.a. (sem iv)- java programming
M.c.a. (sem   iv)- java programmingM.c.a. (sem   iv)- java programming
M.c.a. (sem iv)- java programmingPraveen Chowdary
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsMichael Heron
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...Philip Schwarz
 
All .net Interview questions
All .net Interview questionsAll .net Interview questions
All .net Interview questionsAsad Masood Qazi
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 

Similar to Flyweight Pattern Explained for Memory Optimization (20)

Introduction to OOP.pptx
Introduction to OOP.pptxIntroduction to OOP.pptx
Introduction to OOP.pptx
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Scriptable Objects in Unity Game Engine (C#)
Scriptable Objects in Unity Game Engine (C#)Scriptable Objects in Unity Game Engine (C#)
Scriptable Objects in Unity Game Engine (C#)
 
Java OOPs Concepts.docx
Java OOPs Concepts.docxJava OOPs Concepts.docx
Java OOPs Concepts.docx
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
 
M.c.a. (sem iv)- java programming
M.c.a. (sem   iv)- java programmingM.c.a. (sem   iv)- java programming
M.c.a. (sem iv)- java programming
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Aem best practices
Aem best practicesAem best practices
Aem best practices
 
Sda 9
Sda   9Sda   9
Sda 9
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
 
Week5 inhertiance
Week5 inhertianceWeek5 inhertiance
Week5 inhertiance
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
All .net Interview questions
All .net Interview questionsAll .net Interview questions
All .net Interview questions
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
CoreData
CoreDataCoreData
CoreData
 

More from Hüseyin Ergin

Is there life after code?
Is there life after code?Is there life after code?
Is there life after code?Hüseyin Ergin
 
SITE - CS Presentation
SITE - CS PresentationSITE - CS Presentation
SITE - CS PresentationHüseyin Ergin
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingHüseyin Ergin
 
Software Versioning with Bitbucket and Eclipse
Software Versioning with Bitbucket and EclipseSoftware Versioning with Bitbucket and Eclipse
Software Versioning with Bitbucket and EclipseHüseyin Ergin
 
From the book: 50 Proven Ways to Be Persuasive
From the book: 50 Proven Ways to Be PersuasiveFrom the book: 50 Proven Ways to Be Persuasive
From the book: 50 Proven Ways to Be PersuasiveHüseyin Ergin
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility PatternHüseyin Ergin
 

More from Hüseyin Ergin (6)

Is there life after code?
Is there life after code?Is there life after code?
Is there life after code?
 
SITE - CS Presentation
SITE - CS PresentationSITE - CS Presentation
SITE - CS Presentation
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Software Versioning with Bitbucket and Eclipse
Software Versioning with Bitbucket and EclipseSoftware Versioning with Bitbucket and Eclipse
Software Versioning with Bitbucket and Eclipse
 
From the book: 50 Proven Ways to Be Persuasive
From the book: 50 Proven Ways to Be PersuasiveFrom the book: 50 Proven Ways to Be Persuasive
From the book: 50 Proven Ways to Be Persuasive
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility Pattern
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 

Flyweight Pattern Explained for Memory Optimization

  • 1. Flyweight Pattern Structural Pattern
  • 2. Motivation  You want to draw a forest of trees!  How would you implement this?  Millions of tree objects in the program?  Memory constraint  What is the optimal solution?  Can we implement it so that we create only 1 tree object? 2
  • 3. Flyweight Pattern  That’s where flyweight comes in!  If the objects you create have so much common properties (like trees, only positions are different).  The activity diagram may be like this with only one instance.  Then, we have to store positions somewhere!  Client can do this for us. 3
  • 4. Definition  Flyweight pattern is a pattern for sharing objects, where each instance does not contain its own state but stores it externally.  This allows efficient sharing of objects to save space when there are many instances but only a few different types. 4
  • 5. Text Document Example  You want to hold a text document with so many customizations as style.  Each letter in with a different object?  Creating the letter ‘E’, may be already there before, but with a different style!  So we will have a CharFactory to return us the already created instance OR creates it from scratch! 5
  • 7. Participants  Flyweight  Letter as an abstract class  SharedConcreteFlyweight  LetterA  UnsharedConcreteFlyweight  Not all flyweights must be shared!  Row information for example  FlyweightFactory  Creates and manages flyweights (Character factory)  Client  The styles are stored here, also call to factory 7
  • 8. Intrinsic & Extrinsic States  From course slides (7.Quality of Design)  B is extrinsic to A if A can be fully defined with no notion of B  E.g., class Dog is extrinsic to class Person  B is intrinsic to A if B captures some characteristics inherent to A  E.g., class Date is intrinsic to class Person (by date of birth)  What is with us?  Extrinsic states may be stored in client!  Intrinsic states may be stored in flyweight itself! 8
  • 10. Applicability  Use flyweight pattern iff:  You will use large number of objects.  You want to reduce storage costs.  Most of object states can be extrinsic.  Many group of objects > Fewer shared objects with states  App doesnot care object identity.  Ex: Drawing lots of circles with different colors and sizes 10
  • 11. Consequences  Run time costs  Client is responsible for extrinsic states (storing, fetching etc)  Normally they are part of the object.  Space saving  Will increase as more flyweights are shared.  How much you share, that much you save space!  Factory  Flyweight must be created only via factory! 11
  • 12. Demo  Circle Drawing. (ref at the end)  We want to draw10000 circles in 6 different colors.  Circles have color in common. (intrinsic state)  Position and radius information is given as extrinsic state. (randomly generated) 12
  • 13. Implementation Issues  Storing extrinsic states can be tricky  An object structure for extrinsic states  In text document example, you can store a map of typographic information in seperate structure, instead of storing the font and style information with each object.  This map can keep track of numbers of characters with same attribute.  Accessing a specific object  We have to design the system according to that need.  In drawing tree example, we just draw and go.  We can make the access with a pointer. 13
  • 14. Implementation Issues  Extrinsic states can be stored but what about we want to change the intrinsic state of a flyweight?  Modify the factory as to create new flyweights with a different intrinsic state also.  Not so efficient, slowly breaking the flyweight pattern.  UnsharedConcreteFlyweight is normally a totally different object but we can also make them sharable via factory.  If they become sharable later, the oldly created ones should be added to factory. 14
  • 15. Relation with Other Patterns  You can combine Composite pattern with Flyweight.  Each UnsharedConcreteFlyweight may be component with SharedConcreteFlyweights as children.  In text document: Rows are components or UnsharedConcFly. Letters are leafs or SharedConcFly. 15
  • 16. Relation with Other Patterns – cont’d  FlyweightFactory produces flyweights as in Factory Method.  No abstract Creator (but we can)  FlyweightFactory is the ConcreteCreator.  Flyweight is Product.  Subclasses of Flyweight is ConcreteProducts.  It only looks for an already created instance instead of returning new ConcreteProduct() immediately. 16
  • 17. Relation with Other Patterns – cont’d  In State Pattern, you can share states with Flyweight Pattern.  Flyweight is State.  SharedConcreteFlyweight is ConcreteState.  Client is Context.  With that way, Context can share states if the state is already created.  Handle method may also get extrinsic state as parameter. 17
  • 18. Relation with Other Patterns – cont’d  The same logic works with the Strategy Pattern.  Strategy can be shared, and algorithm can be run with only different inputs (extrinsic state).  The algorithm itself is the intrinsic state.  Difference is: flyweights can be used in many context but strategy is in one context. 18
  • 19. Practical Example  Strings in Java language.  If you don’t explicitly construct a string and put the value with assignment operator, they will be same.  Actually Java has another method called intern for sharing strings. 19
  • 20. Thanks Questions? 20
  • 21. References  GoF Design Patterns Book  Definition from: C# design patterns, James cooper  http://www.dofactory.com/Patterns/PatternFlyweight. aspx#_self1  http://fc07.deviantart.net/fs32/f/2008/218/8/7/Pine_fo rest_by_softwalls.jpg  Oreilly Head First: Design Patterns Book  Fry of Futurama for Questions Picture  Demo: http://www.javacamp.org/designPattern/flyweight.htm l  http://javatechniques.com/public/java/docs/basics/stri ng-equality.html 21

Editor's Notes

  1. After creating instance or getting the created one, we can apply new state to it.Rows here!
  2. Intrinsic and extrinsic states later!