Flyweight pattern

Flyweight pattern
Flyweight UML class diagram.svg

Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. The term is named after the boxing weight class[citation needed]. Often some parts of the object state can 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.

A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this 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 internally.

In other contexts the idea of sharing identical data structures is called hash consing.

Example (java)

// Flyweight object
public interface CoffeeOrder {
    public void serveCoffee(CoffeeOrderContext context);
}


// ConcreteFlyweight object that creates ConcreteFlyweight 
public class CoffeeFlavor implements CoffeeOrder {
    String flavor;
 
    CoffeeFlavor(String newFlavor) {
        flavor = newFlavor;
    }
 
    public String getFlavor() {
        return this.flavor;
    }
 
    public void serveCoffee(CoffeeOrderContext context) {
        System.out.println("Serving Coffee flavor " + flavor + " to table number " + context.getTable());
    }
}


public class CoffeeOrderContext {
   int tableNumber;
 
   CoffeeOrderContext(int tableNumber) {
       this.tableNumber = tableNumber;
   }
 
   public int getTable() {
       return this.tableNumber;
   }
}


import java.util.HashMap;
import java.util.Map;
 
//FlyweightFactory object
public class CoffeeFlavorFactory {
    Map<String, CoffeeFlavor> flavors = new HashMap<String, CoffeeFlavor>();
 
    public CoffeeFlavor getCoffeeFlavor(String flavorName) {
        CoffeeFlavor flavor = flavors.get(flavorName);
        if (flavor == null) {
            flavor = new CoffeeFlavor(flavorName);
            flavors.put(flavorName, flavor);
        }
        return flavor;
    }
 
    public int getTotalCoffeeFlavorsMade() {
        return flavors.size();
    }
}


class TestFlyweight {
   static CoffeeFlavor[] flavors = new CoffeeFlavor[100]; // the flavors ordered
   static CoffeeOrderContext[] tables = new CoffeeOrderContext[100]; // the tables for the orders
   static int ordersMade = 0;
   static CoffeeFlavorFactory flavorFactory;
 
   static void takeOrders(String flavorIn, int table) {
       flavors[ordersMade] = flavorFactory.getCoffeeFlavor(flavorIn);
       tables[ordersMade++] = new CoffeeOrderContext(table);
   }
 
   public static void main(String[] args) {
       flavorFactory = new CoffeeFlavorFactory();
 
       takeOrders("Cappuccino", 2);
       takeOrders("Cappuccino", 2);
       takeOrders("Frappe", 1);
       takeOrders("Frappe", 1);
       takeOrders("Xpresso", 1);
       takeOrders("Frappe", 897);
       takeOrders("Cappuccino", 97);
       takeOrders("Cappuccino", 97);
       takeOrders("Frappe", 3);
       takeOrders("Xpresso", 3);
       takeOrders("Cappuccino", 3);
       takeOrders("Xpresso", 96);
       takeOrders("Frappe", 552);
       takeOrders("Cappuccino", 121);
       takeOrders("Xpresso", 121);
 
       for (int i = 0; i < ordersMade; ++i) {
           flavors[i].serveCoffee(tables[i]);
       }
       System.out.println(" ");
       System.out.println("total CoffeeFlavor objects made: " +  flavorFactory.getTotalCoffeeFlavorsMade());
   }
}

External links


Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • flyweight pattern — noun (object oriented computing) a design pattern in which an object contains no pointers to data type methods …   Wiktionary

  • Flyweight (disambiguation) — Flyweight may mean: * Flyweight pattern, a software design pattern in computer science; * Flyweight, a class in boxing; * Flyweight (MMA), a class in mixed martial arts …   Wikipedia

  • Design Pattern — Patron de conception Pour les articles homonymes, voir Patron. Un patron de conception (design pattern en anglais) est un concept de génie logiciel destiné à résoudre les problèmes récurrents suivant le paradigme objet. En français on utilise… …   Wikipédia en Français

  • Design pattern — Patron de conception Pour les articles homonymes, voir Patron. Un patron de conception (design pattern en anglais) est un concept de génie logiciel destiné à résoudre les problèmes récurrents suivant le paradigme objet. En français on utilise… …   Wikipédia en Français

  • Proxy pattern — Proxy in UML Proxy in …   Wikipedia

  • Structural pattern — In Software Engineering, Structural Design Patterns are Design Patterns that ease the design by identifying a simple way to realize relationships between entities.Examples of Structural Patterns include:* Adapter pattern: adapts one interface for …   Wikipedia

  • Software design pattern — In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a… …   Wikipedia

  • Singleton Pattern — Das Singleton (auch Einzelstück genannt) ist ein in der Softwareentwicklung eingesetztes Entwurfsmuster und gehört zur Kategorie der Erzeugungsmuster (engl. Creational Patterns). Es verhindert, dass von einer Klasse mehr als ein Objekt erzeugt… …   Deutsch Wikipedia

  • Design Pattern — Entwurfsmuster (engl. design pattern) sind bewährte Lösungs Schablonen für wiederkehrende Entwurfsprobleme der Softwarearchitektur und Softwareentwicklung. Sie stellen damit eine wiederverwendbare Vorlage zur Problemlösung dar, die in einem… …   Deutsch Wikipedia

  • Design pattern — Entwurfsmuster (engl. design pattern) sind bewährte Lösungs Schablonen für wiederkehrende Entwurfsprobleme der Softwarearchitektur und Softwareentwicklung. Sie stellen damit eine wiederverwendbare Vorlage zur Problemlösung dar, die in einem… …   Deutsch Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”