Flyweight pattern

The Flyweight, also called flyweight (English flyweight pattern ) is a design pattern in the field of software development and belongs to the category of structural patterns (structural patterns). The flyweight is a design pattern known as the GoF patterns.

Use

The flyweight is used when a large number is required by objects that share certain variable information and disproportionate require a conventional implementation and a lot of resources alone, the number would lead to problems. A part of the state of these objects can be stored in the context ( extrinsic). After removal of the state of reducing the number of different objects to a manageable size.

UML diagram

Actors

The flyweight is abstract and defines the interface for objects that receive and process an externally visible state. The concrete flyweight ( concrete flyweight ) implements the Flyweight interface. If necessary, an internal state is completed. Copies of KonkretesFliegengewicht or derived classes are shared. The intrinsic state must be independent of the context.

The separately used concrete flyweight ( unshared concrete flyweight ) implements this interface also, but contains the complete state. This means that these objects are not shared. This is no longer a question in the narrow sense to fly weights. It can be real " heavyweights " hide behind even. Rather, it indicates the location, find the "normal" objects their place in the pattern.

The Flyweight Factory ( flyweight factory ) creates and manages flyweights. They shall also ensure the correct use of shared objects. The Client ( client) manages references to flyweights and the extrinsic state of the flyweights.

Benefits

The method reduces storage cost proportional to the size of the outsourced state and the number of flyweights. The storage costs are reduced further if the outsourced state need not be stored, but can be calculated.

Disadvantages

The complexity increases relatively strong, especially in designs that use flyweight together with compound. A proper documentation of responsibilities is a must. The runtime costs may rise because the outsourced state retrieved and must be passed to the flyweight when the method call. You continue to rise if the state is calculated.

Example

The graphical representation of a text document.

It can easily consist of hundreds of thousands or even millions of characters and thus drawing objects. Each byte that is stored in the drawing object, is thus perhaps a megabyte. It is readily apparent that it is unacceptable, all the information required by the drawing object to actually save the object.

The drawing object is located in a row object ( compound ). The line number and the Y coordinate on the screen are the same for all characters of the line. You will be transferred to the row object. The column number and the x-coordinate will be apparent from the position in the line. The row object is responsible to calculate this. Font attributes are usually the same for adjacent characters. They are also outsourced.

What remains alone of the code of the character. Thus, there is at the end only a few hundred characters of different objects (at least for alphabet fonts).

Sample code in Java

/ / Flyweight object interface public interface Order { Coffee      public void serve coffee (Coffee Order context); }   / / ConcreteFlyweight object did Creates ConcreteFlyweight public class Coffee Flavor Coffee implements Order {      private String flavor;        public Coffee Flavor (String newFlavor ) {          this.flavor = newFlavor;      }        public String getFlavor () {          return this.flavor;      }        public void serve coffee (Coffee Order context) {          System.out.println (" Serving Coffee flavor" flavor " to table number" context.getTable ());      } }   public class Context { Coffee Order     private int table number;       public Coffee Order Context ( int table number ) {         this.tableNumber = table number;     }       public int getTable () {         return this.tableNumber;     } }   import java.util.HashMap; import java.util.Map;   / / FlyweightFactory object public class Coffee Flavor Factory {      private String, Map CoffeeFlavor> flavors = new HashMap String, CoffeeFlavor> ();        public Coffee Flavor getCoffeeFlavor (String flavor name) {          Coffee Flavor flavor = flavors.get ( flavor name);          if ( flavor == null) {              flavor = new Coffee Flavor ( flavor name);              flavors.put ( name flavor, flavor);          }          return flavor;      }        public int getTotalCoffeeFlavorsMade () {          return flavors.size ();      } }   public class TestFlyweight {     / ** The flavors ordered. * /     private static Coffee Flavor [ ] flavors = new Coffee Flavor;     / ** The tables for the orders. * /     private static Coffee Order Context [ ] tables = new Coffee Order Context;     private static int order made ​​= 0;     private static Coffee Flavor Factory flavor factory;       public static void take orders (String flavorIn, int table ) {         flavors [order made ​​] = flavorFactory.getCoffeeFlavor ( flavorIn );         tables [order made ​​ ] = new Coffee Order Context ( table );     }       public static void main ( String [ ] args ) {         flavor factory = new Coffee Flavor Factory ();        / ** Is Caching of flavors in a HashMap in the Factory            each produced only one object of the same taste, thus saving storage space. * /         take orders ( "Cappuccino ", 2);         take orders ( "Cappuccino ", 2);         take orders ( " frappe ", 1);         take orders ( " frappe ", 1);         take orders ( " Xpresso ", 1);         take orders ( " frappe ", 897 );         take orders ( "Cappuccino ", 97);         take orders ( "Cappuccino ", 97);         take orders ( " frappe ", 3);         take orders ( " Xpresso ", 3);         take orders ( "Cappuccino ", 3);         take orders ( " Xpresso ", 96);         take orders ( " frappe ", 552 );         take orders ( "Cappuccino ", 121);         take orders ( " Xpresso ", 121);           for (int i = 0; i < order made ​​; i) {             flavors [i ] serve coffee ( tables [i]). ;         }         System.out.println ( "");         System.out.println ( "total Coffee Flavor objects made ​​:" flavorFactory.getTotalCoffeeFlavorsMade ());     } } Use in the analysis

Flyweight is a pure design patterns, since its use has mainly been driven by the design aspect space ( next may on the aspect of a very central update the global state ). The use of flyweight in the analysis is therefore usually a code smell.

Related Design Patterns

The compound offers itself to fly weights to hierarchical structures put together ( for example, character, line, paragraph, etc. )

A factory method is needed to generate the flyweights.

Also for state and strategy objects the flyweight pattern is advantageous.

The idiom " immutable object" is closely related to the flyweight. Flyweights should always be designed as " immutable objects".

Itemization

Abstract Factory | Builder | Factory Method | Prototype | Singleton

Adapter | Bridge | Decorator | Facade | Flyweight | Composite | Deputy

Observer | Visitors | Interpreter | Iterator | command | Memento | template method | strategy | Operators | state | Chain of Responsibility

Multitone | Object Pool

Interceptor | null object | protocol stack

Business Delegate | Repository | Data Access Object | Transfer Object | Dependency Injection | Extension Interface | Fluent Interface | Inversion of Control ( IoC ) | Model View Presenter ( MVP ) | Model View ViewModel ( MVVM ) | Thread Pool | Service Locator

  • Structural patterns
  • Gang of four design pattern
338127
de