DEV Community 👩‍💻👨‍💻


Posted on

Flyweight Pattern

Use sharing to support large numbers of fine-grained objects efficiently.

Alt Text


  • Flyweight: declares an interface through which flyweights can receive and act on extrinsic state.
  • ConcreteFlyweight: implements the Flyweight interface and adds storage for intrinsic state, if any. A ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic, that is, it must be independent of the ConcreteFlyweight object's context.
  • UnsharedConcreteFlyweight: not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing, but it doesn't enforce it. It is common for UnsharedConcreteFlyweight objects to have ConcreteFlyweight objects as children at some level in the flyweight object structure (as the Row and Column classes have).
  • FlyweightFactory: creates and manages flyweight objects. Ensures that flyweight is shared properly. When a client requests a flyweight, the FlyweightFactory objects assets an existing instance or creates one, if none exists.
  • Client: maintains a reference to flyweight(s). Computes or stores the extrinsic state of flyweight(s).


public class Main {

    public static void main(String[] args) {
        int extrinsicstate = 22;
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight fx = factory.getFlyweight("X");
        Flyweight fy = factory.getFlyweight("Y");
        Flyweight fz = factory.getFlyweight("Z");
        UnsharedConcreteFlyweight fu = new UnsharedConcreteFlyweight();

public class FlyweightFactory {
    private Hashtable<String, Flyweight> flyweights = new Hashtable<>();

    public FlyweightFactory() {
        flyweights.put("X", new ConcreteFlyweight());
        flyweights.put("Y", new ConcreteFlyweight());
        flyweights.put("Z", new ConcreteFlyweight());

    public Flyweight getFlyweight(String key) {
        return ((Flyweight) flyweights.get(key));

public interface Flyweight {
    void operation(int extrinsicstate);

public class ConcreteFlyweight implements Flyweight {

    public void operation(int extrinsicstate) {
        System.out.println("ConcreteFlyweight: " + extrinsicstate);

public class UnsharedConcreteFlyweight implements Flyweight {

    public void operation(int extrinsicstate) {
        System.out.println("UnsharedConcreteFlyweight: " + extrinsicstate);
Enter fullscreen mode Exit fullscreen mode


ConcreteFlyweight: 21
ConcreteFlyweight: 20
ConcreteFlyweight: 19
UnsharedConcreteFlyweight: 18
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.