Showing posts with label Flyweight Pattern. Show all posts
Showing posts with label Flyweight Pattern. Show all posts

Thursday, 28 November 2013

Flyweight Design pattern - Implementation

Master Software Design Patterns!

Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

SUBSCRIBE NOW

Why Use the Flyweight Design Pattern?

Imagine your application needs to render hundreds of thousands of graphical elements (like circles with various colors). If you instantiate a brand-new object using the new operator for each circle, your application will quickly consume massive amounts of heap memory and slow down.

The Flyweight Pattern is a structural design pattern that solves this problem by sharing common object instances instead of creating duplicate objects. By reusing existing instances, memory consumption drops drastically and overall application performance improves.

Understanding Intrinsic vs Extrinsic State

To successfully implement the Flyweight pattern, divide the object's data into two distinct states:

  • Intrinsic State: Data that is constant, shared across instances, and stored inside the object memory (e.g., the underlying shape definition).
  • Extrinsic State: Data that varies and depends on external context (e.g., color, coordinates, or runtime properties). This data is passed into methods or modified on the fly rather than storing separate objects.

Core Implementation in Java

The Flyweight factory maintains a lookup map (cache) of reusable objects. When a shape is requested, it checks the map first before creating a new instance.

import java.util.HashMap;
import java.util.Map;

// 1. Common Interface
interface Shape {
    void draw();
}

// 2. Concrete Flyweight Class
class Circle implements Shape {
    private String color;
    private int x, y, radius;

    public void setColor(String color) {
        this.color = color;
    }

    public void setX(int x) { this.x = x; }
    public void setY(int y) { this.y = y; }
    public void setRadius(int radius) { this.radius = radius; }

    @Override
    public void draw() {
        System.out.println("Drawing Circle [Color: " + color + 
                           ", X: " + x + ", Y: " + y + 
                           ", Radius: " + radius + 
                           ", HashCode: " + System.identityHashCode(this) + "]");
    }
}

// 3. Flyweight Factory
class ShapeFactory {
    private static final Map<String, Shape> shapeMap = new HashMap<>();

    public static Shape getShape(String shapeType) {
        Shape shape = shapeMap.get(shapeType);

        if (shape == null) {
            if ("CIRCLE".equalsIgnoreCase(shapeType)) {
                shape = new Circle();
                shapeMap.put(shapeType, shape);
                System.out.println("Created new Circle object in memory.");
            }
        }
        return shape;
    }
}

// 4. Demo / Client
public class FlyweightPatternDemo {
    private static final String[] COLORS = { "Red", "Green", "Blue", "Orange", "Black" };

    public static void main(String[] args) {
        for (String color : COLORS) {
            for (int i = 0; i < 2; i++) {
                Circle circle = (Circle) ShapeFactory.getShape("CIRCLE");
                circle.setColor(color);
                circle.setX(i * 10);
                circle.setY(i * 20);
                circle.setRadius(15);
                circle.draw();
            }
        }
    }
}

Watch More Related Design Pattern Tutorials


Click here to watch in Youtube : https://www.youtube.com/watch?v=SKZQx1DdA9U

Click the below Image to Enlarge
Flyweight Design pattern - Implementation

Flyweight Design pattern - Class Diagram



Shape.java

public interface Shape
{
void draw();
}

Circle.java

public class Circle implements Shape
{
private String    color;
private final int x      = 10;
private final int y      = 20;
private final int radius = 30;

public Circle()
{
}

public Circle( String color )
{
this.color = color;
}

public String getColor()
{
return color;
}

public void setColor( String color )
{
this.color = color;
}

@Override
public void draw()
{
System.out.println(this+" : Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :"
               + radius);
}
}

ShapeFactory.java

import java.util.HashMap;

public class ShapeFactory
{
private static final HashMap<String, Shape> shapeMap = new HashMap<String, Shape>();

public static Shape getShape( String shapeType )
{
Shape shape=null;
if( shapeType.equalsIgnoreCase("circle") )
{
shape = (Circle) shapeMap.get("circle");

if( shape == null )
{
shape = new Circle();
shapeMap.put("circle", shape);
System.out.println("Creating circle object with out any color in shapefactory : " + shape
               + "\n");
}
}
return shape;
}
}

FlyweightPatternDemo.java

public class FlyweightPatternDemo
{
private static final String colors[] = { "Red", "Green", "Blue", "Orange", "Black" };

public static void main( String[] args )
{

System.out.println("\n################ Red color Circles ####################");
for( int i = 0; i < 10; ++i )
{
Circle circle = (Circle) ShapeFactory.getShape("circle");
circle.setColor(colors[0]);
circle.draw();
}
System.out.println("\n############### Green color Circles ####################");
for( int i = 0; i < 10; ++i )
{
Circle circle = (Circle) ShapeFactory.getShape("circle");
circle.setColor(colors[1]);
circle.draw();
}
System.out.println("\n################ Blue color Circles ####################");
for( int i = 0; i < 10; ++i )
{
Circle circle = (Circle) ShapeFactory.getShape("circle");
circle.setColor(colors[2]);
circle.draw();
}
System.out.println("\n################ Orange color Circles ####################");
for( int i = 0; i < 10; ++i )
{
Circle circle = (Circle) ShapeFactory.getShape("circle");
circle.setColor(colors[3]);
circle.draw();
}
System.out.println("\n################ Black color Circles ####################");
for( int i = 0; i < 10; ++i )
{
Circle circle = (Circle) ShapeFactory.getShape("circle");
circle.setColor(colors[4]);
circle.draw();
}
}
}

Output

################ Red color Circles ####################
Creating circle object with out any color in shapefactory : Circle@10385c1

Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Red, x : 10, y :20, radius :30

############### Green color Circles ####################
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Green, x : 10, y :20, radius :30

################ Blue color Circles ####################
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Blue, x : 10, y :20, radius :30

################ Orange color Circles ####################
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Orange, x : 10, y :20, radius :30

################ Black color Circles ####################
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30
Circle@10385c1 : Circle: Draw() [Color : Black, x : 10, y :20, radius :30

See also:

  • Flyweight Design pattern - Introduction
  • Flyweight Design pattern - Real Time Example
  • Flyweight Design pattern - Class Diagram
  • Flyweight Design pattern - Sequence Diagram
  • Flyweight Design pattern - Key Points
  • All Design Patterns Links
  • Friday, 22 November 2013

    Flyweight Design pattern - Sequence Diagram

    Master Software Design Patterns!

    Subscribe to Ram N Java for in-depth UML diagrams, clean code architecture, and beginner-friendly programming lessons!

    SUBSCRIBE NOW

    Understanding the Flyweight Sequence Flow

    The Flyweight Design Pattern is a structural pattern focused on minimizing memory footprint by sharing common object instances. While class diagrams show static relationships, a Sequence Diagram demonstrates how messages and execution flow across objects dynamically over time.

    In this workflow, the client never directly instantiates concrete flyweight objects. Instead, every request passes through a centralized factory that acts as an intelligent cache manager.

    Step-by-Step Message Execution Order

    • Step 1: Client Request: The Client sends a request to the FlyweightFactory calling getFlyweight(key).
    • Step 2: Cache Lookup: The FlyweightFactory checks its internal collection (such as a HashMap or pool) for the requested key.
    • Step 3: Conditional Creation:
      • If the object exists, the factory immediately returns the cached instance.
      • If the object does not exist, the factory creates a new ConcreteFlyweight, stores it in the pool, and then returns it.
    • Step 4: Operation Invocation: The Client receives the flyweight instance and calls its operation method, passing any dynamic extrinsic state as method parameters.

    Key Architectural Takeaways

    • Encapsulated Lifecycle: The factory retains full control over when to instantiate and when to reuse shared objects.
    • Context Independence: The flyweight object remains stateless regarding external variations, receiving context on-demand through operation parameters.
    • Scalability: Even under high loads with millions of interactions, the total number of objects in memory stays bounded and predictable.

    Watch More Related Design Pattern Tutorials


    Click here to watch in Youtube : https://www.youtube.com/watch?v=3WAXOUm_WEc


    Click the below Image to Enlarge
    Flyweight Design pattern - Sequence Diagram

















    See also:

  • Flyweight Design pattern - Introduction
  • Flyweight Design pattern - Real Time Example
  • Flyweight Design pattern - Class Diagram
  • Flyweight Design pattern - Implementation
  • Flyweight Design pattern - Key Points
  • All Design Patterns Links
  • Flyweight Design pattern - Class Diagram

    Master Software Architecture!

    Subscribe to Ram N Java for clean code, UML diagram explanations, and beginner-friendly programming lessons!

    SUBSCRIBE NOW

    What is the Flyweight Class Diagram?

    The Flyweight Design Pattern is a structural pattern designed to handle high volumes of fine-grained objects efficiently by sharing common state. The Class Diagram provides a blueprint of the architectural relationships between the participants that make this memory-sharing possible.

    By defining clear responsibilities across separate interfaces and classes, the pattern ensures that shared data remains untouched while context-dependent parameters can be passed in dynamically.

    Key Participants in the Class Diagram

    • Flyweight Interface: Declares the contract and operation methods through which flyweights can receive and act upon extrinsic state passed from the outside.
    • ConcreteFlyweight: Implements the Flyweight interface and stores the internal intrinsic state that is immutable and shared across multiple contexts.
    • UnsharedConcreteFlyweight: Represents instances where sharing is not required or feasible; not all subclasses of the Flyweight interface need to be shared.
    • FlyweightFactory: Manages a pool or cache of existing flyweight objects. When requested, it returns an existing instance from the cache or creates a new one if it does not yet exist.
    • Client: Maintains references to flyweight objects, computes or stores the extrinsic state, and passes it to the flyweight when invoking operations.

    Structural Benefits & Best Practices

    • Strict Object Separation: Clear division between intrinsic (stored inside) and extrinsic (supplied by caller) state keeps memory usage predictable.
    • Centralized Factory Control: The factory enforces object pooling so that duplicate objects with identical intrinsic states are never created.
    • Clean UML Architecture: Easy to interpret and implement across enterprise applications, graphics rendering engines, and document editors.

    Watch More Related Design Pattern Tutorials


    Click here to watch in Youtube : https://www.youtube.com/watch?v=WjBsuNfIoOY

    Click the below Image to Enlarge
    Flyweight Design pattern - Class Diagram

















    See also:

  • Flyweight Design pattern - Introduction
  • Flyweight Design pattern - Real Time Example
  • Flyweight Design pattern - Sequence Diagram
  • Flyweight Design pattern - Implementation
  • Flyweight Design pattern - Key Points
  • All Design Patterns Links
  • Flyweight Design pattern - Keypoints

    Master Software Architecture & Clean Code!

    Subscribe to Ram N Java for essential design pattern summaries, clean code tips, and beginner-friendly programming lessons!

    SUBSCRIBE NOW

    Overview of the Flyweight Design Pattern

    The Flyweight Pattern is a structural design pattern primarily utilized to reduce memory footprint and prevent object bloat. When an application creates a massive volume of similar objects, storing duplicate data across instances quickly leads to memory exhaustion.

    The pattern solves this bottleneck by sharing common object instances across operations rather than instantiating new objects repeatedly.

    Essential Key Points You Must Know

    • Drastic Memory Optimization: Reuses existing, fine-grained objects to keep heap memory usage low and prevent OutOfMemoryError exceptions in large systems.
    • Separation of State:
      • Intrinsic State: Invariant, shared data stored permanently inside the flyweight object.
      • Extrinsic State: Context-dependent data passed in dynamically by the client at runtime.
    • Immutability: The intrinsic state of a flyweight instance must remain immutable so that concurrent operations cannot accidentally alter shared data.
    • Centralized Object Factory: A flyweight factory maintains a lookup cache/pool to manage and return existing instances efficiently.
    • Trade-Off (CPU vs Memory): Saves substantial memory at the cost of slight runtime lookup overhead and passing extrinsic data across method calls.

    When to Use Flyweight

    Adopt the Flyweight pattern when:

    • An application instantiates a massive number of small objects.
    • High memory consumption creates a noticeable performance bottleneck.
    • Most object properties can be separated into shared intrinsic properties and calculated extrinsic values.

    Watch More Related Structural Pattern Tutorials


    Click here to watch in Youtube : https://www.youtube.com/watch?v=Ht-ieqGMKBk

    Click the below Image to Enlarge
















    See also:

  • Flyweight Design pattern - Introduction
  • Flyweight Design pattern - Real Time Example
  • Flyweight Design pattern - Class Diagram
  • Flyweight Design pattern - Sequence Diagram
  • Flyweight Design pattern - Implementation
  • All Design Patterns Links
  • Flyweight Design pattern - Real Time Example

    Master Software Architecture & Clean Code!

    Subscribe to Ram N Java for hands-on design pattern breakdowns, real-world examples, and clean Java programming guides!

    SUBSCRIBE NOW

    Why Look at Real-Time Examples?

    The Flyweight Design Pattern is best understood through practical, real-world scenarios where system resources are constrained. In systems rendering thousands of graphical elements, text characters, or gaming assets, creating an independent object for every single item causes memory usage to explode.

    By identifying what can be shared and reusing existing object instances, the Flyweight pattern drastically lowers memory overhead while keeping your application fast and responsive.

    Real-World Use Cases for Flyweight

    • Text Processors & Document Editors: Instead of allocating an object for every character on a page, the editor shares a single character instance (e.g., the letter 'A' with font glyph data) and supplies position coordinates externally.
    • Gaming Engines: In games with massive forests or battlefields, thousands of trees or soldiers share 3D meshes, textures, and models (intrinsic state), while their unique coordinate positions and health points (extrinsic state) are supplied dynamically.
    • GUI & Graphic Rendering: Drawing thousands of shapes, circles, or icons where geometric formulas and underlying rendering styles are shared across coordinates.
    • Java Standard Library (Caching): Built-in implementations like Integer.valueOf() or String.intern() cache and reuse common values rather than constructing new heap objects.

    Key Principles in Action

    • Immutable Shared State: The shared intrinsic data must never change during execution to prevent unexpected side effects across consumers.
    • Separation of Concerns: Callers maintain variable context (coordinates, colors, timestamps) and pass it into flyweight methods when needed.
    • Pool / Cache Management: A factory handles object pooling, ensuring an object is created only when it doesn't already exist in the pool.

    Watch More Related Design Pattern Tutorials


    Click here to watch in Youtube : https://www.youtube.com/watch?v=y2Qpu4c-wN4

    Click the below Image to Enlarge
    Flyweight Design pattern - Real Time Example

















    See also:

  • Flyweight Design pattern - Introduction
  • Flyweight Design pattern - Class Diagram
  • Flyweight Design pattern - Sequence Diagram
  • Flyweight Design pattern - Implementation
  • Flyweight Design pattern - Key Points
  • All Design Patterns Links
  • Flyweight Design pattern - Introduction

    Master Software Architecture & Clean Code!

    Subscribe to Ram N Java for core software design patterns, clean coding techniques, and comprehensive Java guides!

    SUBSCRIBE NOW

    Introduction to the Flyweight Pattern

    The Flyweight Design Pattern is a structural design pattern primarily used to optimize memory usage by sharing common data across multiple objects instead of keeping identical data in every single instance.

    When an application requires a large number of objects that share significant amounts of state, creating separate instances quickly consumes JVM heap space and impacts performance. The Flyweight pattern prevents this by reusing existing matching objects from a shared pool.

    Understanding Intrinsic vs. Extrinsic State

    The fundamental concept behind the Flyweight pattern is splitting an object's state into two distinct categories:

    • Intrinsic State: Constant, immutable data stored internally within the flyweight object. This state is context-independent and can be safely shared across different callers.
    • Extrinsic State: Variable, context-dependent data that changes based on where and when the object is used. The client maintains this state and passes it to the flyweight method during execution.

    Core Structural Components

    • Flyweight Interface: Outlines the operations that flyweight instances perform, accepting extrinsic data as parameters.
    • Concrete Flyweight: Implements the interface and holds the intrinsic state.
    • Flyweight Factory: Manages the pool/cache of flyweights, returning existing instances or creating new ones on demand.
    • Client: Holds or computes extrinsic values and requests flyweights via the factory.

    Watch More Related Design Pattern Tutorials


    Click here to watch in Youtube : https://www.youtube.com/watch?v=lY3ilaxi-7o

    Click the below Image to Enlarge
    Flyweight Design pattern - Introduction

















    See also:

  • Flyweight Design pattern - Real Time Example
  • Flyweight Design pattern - Class Diagram
  • Flyweight Design pattern - Sequence Diagram
  • Flyweight Design pattern - Implementation
  • Flyweight Design pattern - Key Points
  • All Design Patterns Links
  • Tutorials