Flyweight
Definition
Use sharing to support large numbers of fine-grained objects efficiently.
UML class diagram
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.
- 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.
- FlyweightFactory
- creates and manages flyweight objects
- ensures that flyweight are 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.
- computes or stores the extrinsic state of flyweight.
Sample code in Java
package com.hong.flyweight; import java.util.HashMap; interface Flyweight{ public void operation(int extrinsicstate); } class ConcreteFlyweight implements Flyweight{ @Override public void operation(int extrinsicstate) { System.out.println("ConcreteFlyweight: " + extrinsicstate); } } class FlyweightFactory { private HashMap<String, Flyweight> flyweights = new HashMap<String, Flyweight>(); public FlyweightFactory() { flyweights.put("A", new ConcreteFlyweight()); flyweights.put("B", new ConcreteFlyweight()); } public Flyweight getFlyweight(String key) { if(!flyweights.containsKey(key)) flyweights.put(key, new ConcreteFlyweight()); return flyweights.get(key); } } class UnsharedFlyweight implements Flyweight { @Override public void operation(int extrinsicstate){ System.out.println("UnsharedFlyweight: " + extrinsicstate); } } public class Flyweight_structure { public static void main(String[] args) { FlyweightFactory factory = new FlyweightFactory(); Flyweight flyweight_one = factory.getFlyweight("A"); Flyweight flyweight_two = factory.getFlyweight("B"); Flyweight flyweight_three = factory.getFlyweight("C"); flyweight_one.operation(1); flyweight_one.operation(2); flyweight_one.operation(3); } }