|
Flyweight is a software design pattern. A Flyweight is an object that minimizes memory occupation by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple representation would use an unacceptable amount of memory. Often some parts of the object state cannot be shared and it's common to put them in external data structures and pass them to the flyweight objects temporarily when they are used. In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. ...
A classic example usage of the flyweight pattern are the data structures for graphical representation of characters in a word processor. It would be nice to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but it would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored externally. A word processor (also more formally known as a document preparation system) is a computer application used for the production (including composition, editing, formatting, and possibly printing) of any sort of viewable or printed material. ...
For referencing in Wikipedia, see Wikipedia:Citing sources. ...
Examples The following programs illustrate the document example given above: the flyweights are called FontData in the Java example and GraphicChar in the C# example.
Java public enum FontEffect { BOLD, ITALIC, SUPERSCRIPT, SUBSCRIPT, STRIKETHROUGH } public final class FontData { /** * A weak hash map will drop unused references to FontData. * Values have to be wrapped in WeakReferences, * because value objects in weak hash map are held by strong references. */ private static final WeakHashMap<FontData, WeakReference<FontData>> flyweightData = new WeakHashMap<FontData, WeakReference<FontData>>(); private final int pointSize; private final String fontFace; private final Color color; private final Set<FontEffect> effects; private FontData(int pointSize, String fontFace, Color color, EnumSet<FontEffect> effects) { this.pointSize = pointSize; this.fontFace = fontFace; this.color = color; this.effects = Collections.unmodifiableSet(effects); } public static FontData create(int pointSize, String fontFace, Color color, FontEffect... effects) { EnumSet<FontEffect> effectsSet = EnumSet.noneOf(FontEffect.class); for (FontEffect fontEffect : effects) { effectsSet.add(fontEffect); } // We are unconcerned with object creation cost, we are reducing overall memory consumption FontData data = new FontData(pointSize, fontFace, color, effectsSet); if (!flyweightData.containsKey(data)) { flyweightData.put(data, new WeakReference(data)); } // return the single immutable copy with the given values return flyweightData.get(data).get(); } @Override public boolean equals(Object obj) { if (obj instanceof FontData) { if (obj == this) { return true; } FontData other = (FontData) obj; return other.pointSize == pointSize && other.fontFace.equals(fontFace) && other.color.equals(color) && other.effects.equals(effects); } return false; } @Override public int hashCode() { return (pointSize * 37 + effects.hashCode() * 13) * fontFace.hashCode(); } // Getters for the font data, but no setters. FontData is immutable. } C# using System.Collections; using System.Collections.Generic; using System; class GraphicChar { char c; string fontFace; public GraphicChar(char c, string fontFace) { this.c = c; this.fontFace = fontFace; } public static void printAtPosition(GraphicChar c, int x, int y) { Console.WriteLine("Printing '" + c.c + "' in '{1}' at position {2}:{3}.", c.c, c.fontFace, x, y); } } class GraphicCharFactory { Hashtable pool = new Hashtable(); // the Flyweights public int getNum() { return pool.Count; } public GraphicChar get(char c, string fontFace) { GraphicChar gc; string key = c.ToString() + fontFace; gc = (GraphicChar)pool[key]; if (gc == null) { gc = new GraphicChar(c, fontFace); pool.Add(key, gc); } return gc; } } class FlyWeightExample { public static void Main(string[] args) { GraphicCharFactory cf = new GraphicCharFactory(); // Compose the text by storing the characters as objects. List<GraphicChar> text = new List<GraphicChar>(); text.Add(cf.get('H', "Arial")); // 'H' and "Arial" are called intrinsic information text.Add(cf.get('e', "Arial")); // because it is stored in the object itself. text.Add(cf.get('l', "Arial")); text.Add(cf.get('l', "Arial")); text.Add(cf.get('o', "Times")); // See how the Flyweight approach is beginning to save space: Console.WriteLine("CharFactory created only {0} objects for {1} characters.", cf.getNum(), text.Count); int x=0, y=0; foreach (GraphicChar c in text) { // Passing position as extrinsic information to the objects, GraphicChar.printAtPosition(c, x++, y); // as a top-left 'A' is not different to a top-right one. } } } External links - Flyweight pattern discussion with 1-page examples by Vince Huston
| Design patterns in Design Patterns | Creational: Abstract factory • Builder • Factory • Prototype • Singleton David C. Geary is a notable United States cognitive developmental psychologist with interests in mathematical learning and in evolution. ...
Neal Ford was born in Montreal in 1965. ...
In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. ...
This article is about the book by Gamma et al. ...
A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. ...
The Builder Pattern is a software design pattern. ...
The factory method pattern is an object-oriented design pattern. ...
A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. ...
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. ...
Structural: Adapter • Bridge • Composite • Decorator • Façade • Flyweight • Proxy In computer programming, the adapter design pattern (often referred to as the wrapper pattern or simply a wrapper) adapts one interface for a class into one that a client expects. ...
The bridge pattern is a design pattern used in software engineering which is meant to decouple an abstraction from its implementation so that the two can vary independently (Gamma et. ...
This does not cite any references or sources. ...
For decorators in Python, see Python syntax and semantics#Decorators. ...
The façade pattern is an object-oriented design pattern. ...
// In computer programming, the proxy pattern is a software design pattern. ...
Behavioral: Chain of responsibility • Command • Interpreter • Iterator • Mediator • Memento • Observer • State • Strategy • Template method • Visitor In Object Oriented Design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. ...
In object-oriented programming, the Command pattern is a design pattern in which objects are used to represent actions. ...
In computer programming, the interpreter pattern is a particular design pattern. ...
In object-oriented programming, an iterator is an object allowing one to sequence through all of the elements or parts contained in some other object, typically a container or list. ...
The mediator pattern is a software design pattern that provides a unified interface to a set of interfaces in a subsystem. ...
The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo by rollback). ...
The observer pattern (sometimes known as publish/subscribe) is a design pattern used in computer programming to observe the state of an object in a program. ...
A behavioral software design pattern, state pattern is used in computer programming to represent the state of an object. ...
In computer programming, the strategy pattern is a particular software design pattern, whereby algorithms can be selected on-the-fly at runtime. ...
Template method: UML class diagram. ...
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure. ...
| |