Example of flyweight Design Patterns

Problem Statement:

Here, we’ll create a ‘CoffeeOrder’ system where each order has intrinsic state (type of coffee) and extrinsic state (table number). so we will use Flyweight method pattern here to solve this case.

Overall Code for the above example:

Java




import java.util.HashMap;
import java.util.Map;
 
// Flyweight interface
interface CoffeeOrder {
    void serveCoffee(CoffeeOrderContext context);
}
 
// ConcreteFlyweight
class CoffeeFlavor implements CoffeeOrder {
    private final String flavor;
 
    public CoffeeFlavor(String flavor) {
        this.flavor = flavor;
    }
 
    @Override
    public void serveCoffee(CoffeeOrderContext context) {
        System.out.println("Serving coffee flavor " + flavor + " to table " + context.getTableNumber());
    }
}
 
// Context class to hold extrinsic state
class CoffeeOrderContext {
    private final int tableNumber;
 
    public CoffeeOrderContext(int tableNumber) {
        this.tableNumber = tableNumber;
    }
 
    public int getTableNumber() {
        return tableNumber;
    }
}
 
// Flyweight factory
class CoffeeOrderFactory {
    private final Map<String, CoffeeOrder> flavors = new HashMap<>();
 
    public CoffeeOrder getCoffeeOrder(String flavor) {
        CoffeeOrder coffeeOrder = flavors.get(flavor);
 
        if (coffeeOrder == null) {
            coffeeOrder = new CoffeeFlavor(flavor);
            flavors.put(flavor, coffeeOrder);
        }
 
        return coffeeOrder;
    }
}
 
// Client code
public class CoffeeShop {
    public static void main(String[] args) {
        CoffeeOrderFactory coffeeOrderFactory = new CoffeeOrderFactory();
 
        // Orders with intrinsic state (coffee flavor) and extrinsic state (table number)
        CoffeeOrder order1 = coffeeOrderFactory.getCoffeeOrder("Cappuccino");
        order1.serveCoffee(new CoffeeOrderContext(1));
 
        CoffeeOrder order2 = coffeeOrderFactory.getCoffeeOrder("Espresso");
        order2.serveCoffee(new CoffeeOrderContext(2));
 
        CoffeeOrder order3 = coffeeOrderFactory.getCoffeeOrder("Cappuccino");
        order3.serveCoffee(new CoffeeOrderContext(3));
 
        // The flavor "Cappuccino" is shared between order1 and order3
        // It reduces memory usage as the intrinsic state is shared among orders with the same flavor
    }
}


Output

Serving coffee flavor Cappuccino to table 1
Serving coffee flavor Espresso to table 2
Serving coffee flavor Cappuccino to table 3




Explanation of the above example:

In this example,

  • ‘CoffeeFlavor’ represents the concrete flyweight, and ‘CoffeeOrderContext’ represents the extrinsic state.
  • ‘CoffeeOrderFactory’ is responsible for managing and creating flyweights, ensuring that shared flyweights are reused.
  • The client code (‘CoffeeShop’) demonstrates how the flyweights are used to create and serve coffee orders with intrinsic and extrinsic states.

Diagrammatic Representation of Flyweight Design Pattern in Java

Explanation

In the above figure:

  • Flyweight Interface: This interface declares a method through which flyweights can receive and act on extrinsic state.
  • ConcreteFlyweight: This class implements the Flyweight interface and represents concrete flyweights. These objects share state that is intrinsic to them.
  • UnsharedConcreteFlyweight: Some flyweight implementations may not be shared. In such cases, the unshared concrete flyweight is created.
  • FlyweightFactory: This class is responsible for creating and managing flyweight objects. It ensures that flyweights are shared and reused when appropriate.
  • Client: The client maintains a reference to flyweights and computes or stores the extrinsic state.

Flyweight Method Design Pattern in Java

A flyweight design pattern or flyweight method is defined as a structural pattern that is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects.

The key idea behind the Flyweight pattern is to use shared objects to support large numbers of fine-grained objects efficiently.

Important Topics for Flyweight Design Patterns

  • Key Component of Flyweight Design Patterns:
  • Example of flyweight Design Patterns:
  • Use Case of Flyweight Design Patterns in Java
  • Advantages of Flyweight Design Patterns in Java
  • Disadvantages of Flyweight Design Patterns in Java

Similar Reads

Key Component of Flyweight Design Patterns:

Flyweight Interface/Abstract Class: Define an interface or an abstract class that declares the methods that must be implemented by concrete flyweight objects. This interface usually represents the common functionality shared among the flyweight objects....

Example of flyweight Design Patterns:

...

Use Case of Flyweight Design Patterns in Java

...

Advantages of Flyweight Design Patterns in Java

...

Disadvantages of Flyweight Design Patterns in Java

...