DEV Community

eidher
eidher

Posted on • Updated on

Flyweight Pattern

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

Alt Text

Participants

  • 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).

Code

public class Main {

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

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 {

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

public class UnsharedConcreteFlyweight implements Flyweight {

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

Output

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

Top comments (0)