Flyweight Design Pattern
Structural pattern. Structural design patterns are concerned with composing classes and objects into larger structures.
Intent: "Use sharing to support large numbers of fine-grained objects efficiently." [GoF]
Open in the interactive referenceDownload the PDF reference
Intent
The intent of the Flyweight design pattern is to:
"Use sharing to support large numbers of fine-grained
objects efficiently."
[GoF]
See Problem and Solution
sections for a more structured description of the intent.
-
The Flyweight design pattern solves problems like:
- How can large numbers of fine-grained objects be supported efficiently?
- For example, to represent a text document at the finest levels, an object is needed for every character in the document, which may result in a huge amount of objects.
-
The Flyweight pattern describes how to solve such
problems:
-
Use sharing to support large numbers of fine-grained
objects efficiently.
-
Define
Flyweightobjects that store intrinsic (invariant) state.
Clients shareFlyweightobjects and pass in extrinsic (variant) state dynamically at run-time when they invoke a flyweight operation (flyweight.operation(extrinsicState)). -
Intrinsic state is invariant (context independent)
and therefore can be shared.
Extrinsic state is variant (context dependent) and therefore can not be shared and must be passed in.
-
Use sharing to support large numbers of fine-grained
objects efficiently.
Problem
The Flyweight design pattern solves problems like:
How can large numbers of fine-grained objects
be supported efficiently?
See Applicability section for all problems Flyweight can solve.
See Solution section for how Flyweight solves the problems.
- A naive way to support large numbers of objects in an application is to create an object each time it is needed.
-
For example, text editing applications.
To represent a text document at the finest levels, an object is needed for every occurrence of a character in the document, which can result in a huge amount of objects. "Even moderate-sized documents may require hundreds of thousands of character objects, which will consume lots of memory and may incur unacceptable run-time overhead." [GoF, p195] - That's the kind of approach to avoid if we want to support large numbers of objects efficiently.
- It should be possible to reduce the number of physically created objects. Logically, there should be an object for every occurrence of a character in the document.
-
For example, language processing and translation applications.
It should be possible to process any size of documents efficiently.
Solution
The Flyweight design pattern provides a solution:
Define separate Flyweight objects
that store intrinsic (invariant) state.
Clients share Flyweight objects
and pass in extrinsic (variant) state
instead of creating an object each time it is needed.
Describing the Flyweight
design in more detail is the theme of the following sections.
See Applicability section for all problems Flyweight can solve.
-
"The key concept here is the distinction
between intrinsic
and extrinsic state."
[GoF, p196]
Flyweight objects store intrinsic state, and
clients
pass in extrinsic state.
Intrinsic state is invariant (context independent) and therefore can be shared.
For example, the code of a character in the used character set.
Extrinsic state is variant (context dependent) and therefore can not be shared.
For example, the position of a character in the document. -
Define separate
Flyweightobjects:
-
Define an interface
(
Flyweight | operation(extrinsicState)) through which extrinsic (variant) state can be passed in.
-
Define classes (
Flyweight1,…) that implement theFlyweightinterface and store intrinsic (invariant) state that can be shared.
-
Define an interface
(
-
Clients share (reuse)
Flyweightobjects and pass in extrinsic state each time they invoke a flyweight operation (flyweight.operation(extrinsicState)).-
To ensure that
Flyweightobjects are shared properly, clients must obtain flyweights solely from the flyweight factory (getFlyweight(key)) that maintains a pool of sharedFlyweightobjects. - This greatly reduces the number of physically created objects.
-
To ensure that
Motivation
Consider the left design (problem):
-
Large number of physically created objects.
-
To represent a text document,
an object is created for each character
in the
document. -
The number of physically created character objects
depends on
the number of characters in the document.
-
To represent a text document,
an object is created for each character
in the
Consider the right design (solution):
-
Small number of physically created objects.
-
To represent a text document,
a
Flyweightobject is created for each character in the used character set (flyweight pool). -
The number of physically created character objects is
independent of the number
of characters in the document.
It depends on the number of characters in the character set.
-
A flyweight stores only the intrinsic state
(for example, the character code).
Clients provide the extrinsic state dynamically at run-time
(for example, the current position, font, and color of the character in the document).
-
To represent a text document,
a
Applicability
Design Problems
-
Supporting Large Numbers of Objects
- How can large numbers of fine-grained objects be supported efficiently?
- How can objects be shared to avoid creating large numbers of objects?
-
How can small numbers of physically created objects
represent large numbers of logically different objects?
Structure
Static Class Structure
-
Client-
Refers to the
Flyweightinterface. -
Maintains a reference (
flyweight) to aFlyweightobject. -
Passes in extrinsic state when invoking
a
Flyweightoperation (operation(extrinsicState)). -
Requests a
Flyweightobject from theFlyweightFactory(by invokinggetFlyweight(key)).
-
Refers to the
-
Flyweight-
Defines an interface
(
operation(extrinsicState)) through which extrinsic (variant) state can be passed in.
-
Defines an interface
(
-
Flyweight1,…-
Implement
the
Flyweightinterface. - Store intrinsic (invariant) state that can be shared.
-
Implement
the
-
UnsharedFlyweight1,…-
Implement
the
Flyweightinterface but are not shared.
-
Implement
the
-
FlyweightFactory-
Maintains a container of
shared
Flyweightobjects (flyweight pool). -
Creates a
Flyweightobject if it doesn't exist and shares (reuses) an existing one.
-
Maintains a container of
shared
Dynamic Object Collaboration
-
In this sample scenario,
a
Clientobject shares aFlyweight1object by requesting it from aFlyweightFactoryobject. -
The interaction starts with
the
Clientthat callsgetFlyweight(key)on theFlyweightFactory. -
Because the flyweight does not already
exist,
the
FlyweightFactorycreates aFlyweight1object and returns it to theClient. -
The
Clientcallsoperation(extrinsicState)on the returnedFlyweight1object by passing in the extrinsic state. -
Thereafter,
the
Clientagain callsgetFlyweight(key)on theFlyweightFactory. -
Because the flyweight already
exists,
the
FlyweightFactoryshares (reuses) theFlyweight1object. -
The
Clientcallsoperation(extrinsicState)on the returnedFlyweight1object. -
See also Sample Code / Example 1.
Consequences
Advantages (+)
-
Enables abstractions at the
finest levels.
- A small number of physically created objects can represent an open-ended number of logically different objects.
Disadvantages (–)
-
Introduces run-time costs.
- Clients are responsible for passing in extrinsic state dynamically at run-time.
- Storing/retrieving/calculating extrinsic state each time a flyweight operation is performed can impact memory usage and system performance.
-
Provides no reliability on object identity.
- The same physically created object represents many logically different objects.
- Therefore, applications that depend on object identity should not use flyweights.
Implementation
Implementation Issues
-
Flyweight Factory
-
To ensure that
Flyweightobjects are shared properly, clients must obtain flyweights solely from the flyweight factory (getFlyweight(key)). -
A flyweight factory maintains a pool of shared
flyweights.
If the requested flyweight already exists in the pool, it is shared (reused) and returned to the client.
Otherwise, it is created, added to the pool, and returned. -
The
keyparameter in thegetFlyweight(key)operation is needed to look up the right flyweight in the pool (see Sample Code / Example 1).
-
To ensure that
Sample Code 1
Basic Java code for implementing the sample UML diagrams.
1 package com.sample.flyweight.basic;
2 public class Client {
3 // Running the Client class as application.
4 public static void main(String[] args) {
5 Flyweight flyweight;
6 // Getting a FlyweightFactory object.
7 FlyweightFactory flyweightFactory = FlyweightFactory.getInstance();
8
9 flyweight = flyweightFactory.getFlyweight("A");
10 System.out.println(flyweight.operation(100));
11
12 flyweight = flyweightFactory.getFlyweight("A");
13 System.out.println(flyweight.operation(200));
14
15 System.out.println("\n*** Number of flyweights created: "
16 + flyweightFactory.getSize() + " ***");
17 }
18 }
C r e a t i n g a flyweight with key = A
performing an operation on the flyweight
with intrinsic state = A and passed in extrinsic state = 100.
S h a r i n g a flyweight with key = A
performing an operation on the flyweight
with intrinsic state = A and passed in extrinsic state = 200.
*** Number of flyweights created: 1 ***
1 package com.sample.flyweight.basic;
2 public interface Flyweight {
3 public String operation(int extrinsicState);
4 }
1 package com.sample.flyweight.basic;
2 public class Flyweight1 implements Flyweight {
3 private String intrinsicState;
4 public Flyweight1(String intrinsicState) {
5 this.intrinsicState = intrinsicState;
6 }
7 public String operation(int extrinsicState) {
8 return " performing an operation on the flyweight\n "
9 + " with intrinsic state = " + intrinsicState
10 + " and passed in extrinsic state = " + extrinsicState + ".";
11 }
12 }
1 package com.sample.flyweight.basic;
2 import java.util.HashMap;
3 import java.util.Map;
4 public class FlyweightFactory {
5 // Implemented as Singleton.
6 // See also Singleton / Implementation / Variant 1.
7 private static final FlyweightFactory INSTANCE = new FlyweightFactory();
8 private FlyweightFactory() { }
9 public static FlyweightFactory getInstance() {
10 return INSTANCE;
11 }
12 // Shared flyweight pool.
13 private Map<String, Flyweight> flyweights = new HashMap<String, Flyweight>();
14 // Creating and maintaining shared flyweights.
15 public Flyweight getFlyweight(String key) {
16 if (flyweights.containsKey(key)) {
17 System.out.println("S h a r i n g a flyweight with key = " + key);
18 return flyweights.get(key);
19 } else {
20 System.out.println("C r e a t i n g a flyweight with key = " + key);
21 Flyweight flyweight = new Flyweight1(key); // assuming key = intrinsic state
22 flyweights.put(key, flyweight);
23 return flyweight;
24 }
25 }
26 public int getSize() {
27 return flyweights.size();
28 }
29 }