http://en.wikipedia.org/wiki/Flyweight_pattern

In computer programmingflyweight 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. Often some parts of the object state can be shared, and it is common practice to hold 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.

Another example is string interning.

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

Immutability & Equality

To enable safe sharing, between clients and threads, Flyweight objects must be immutable. Flyweight objects are by definition value objects. The identity of the object instance is of no consequence therefore two Flyweight instances of the same value are considered equal.

Concurrency

Special consideration must be made in scenarios where Flyweight objects are created on multiple threads. If the list of values is finite and known in advance the Flyweights can be instantiated ahead of time and retrieved from a container on multiple threads with no contention. If Flyweights are instantiated on multiple threads there are two options:

  1. Make Flyweight instantiation single threaded thus introducing contention and ensuring one instance per value.
  2. Allow concurrent threads to create multiple Flyweight instances thus eliminating contention and allowing multiple instances per value. This option is only viable if the equality criterion is met.

History

According to a textbook Design Patterns: Elements of Reusable Object-Oriented Software,[1] the flyweight pattern was first coined and extensively explored byPaul Calder and Mark Linton in 1990[2] to efficiently handle glyph information in a WYSIWYG document editor, although similar techniques were already used in other systems, e.g., an application framework by Weinand et al. (1988).[3]

Example in Java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; // Instances of CoffeeFlavour will be the Flyweights
class CoffeeFlavour {
private final String name; CoffeeFlavour(String newFlavor) {
this.name = newFlavor;
} @Override
public String toString() {
return name;
}
} // Menu acts as a factory and cache for CoffeeFlavour flyweight objects
class Menu {
private Map<String, CoffeeFlavour> flavours = new HashMap<String, CoffeeFlavour>(); CoffeeFlavour lookup(String flavorName) {
if (!flavours.containsKey(flavorName))
flavours.put(flavorName, new CoffeeFlavour(flavorName));
return flavours.get(flavorName);
} int totalCoffeeFlavoursMade() {
return flavours.size();
}
} class Order {
private final int tableNumber;
private final CoffeeFlavour flavour; Order(int tableNumber, CoffeeFlavour flavor) {
this.tableNumber = tableNumber;
this.flavour = flavor;
} void serve() {
System.out.println("Serving " + flavour + " to table " + tableNumber);
}
} class CoffeeShop {
private final List<Order> orders = new ArrayList<Order>();
private final Menu menu = new Menu(); void takeOrder(String flavourName, int table) {
CoffeeFlavour flavour = menu.lookup(flavourName);
Order order = new Order(table, flavour);
orders.add(order);
} void service() {
for (Order order : orders)
order.serve();
} String report() {
return "\ntotal CoffeeFlavour objects made: "
+ menu.totalCoffeeFlavoursMade();
} public static void main(String[] args) {
CoffeeShop shop = new CoffeeShop(); shop.takeOrder("Cappuccino", 2);
shop.takeOrder("Frappe", 1);
shop.takeOrder("Espresso", 1);
shop.takeOrder("Frappe", 897);
shop.takeOrder("Cappuccino", 97);
shop.takeOrder("Frappe", 3);
shop.takeOrder("Espresso", 3);
shop.takeOrder("Cappuccino", 3);
shop.takeOrder("Espresso", 96);
shop.takeOrder("Frappe", 552);
shop.takeOrder("Cappuccino", 121);
shop.takeOrder("Espresso", 121); shop.service();
System.out.println(shop.report());
}
}

 
 
GoF Patterns
 
 
 
 
Concurrency Patterns
 
Architectural Patterns
 
Other Patterns
 
Books
 
People
 
Communities

Flyweight_pattern--reference的更多相关文章

  1. ASP.NET Core: You must add a reference to assembly mscorlib, version=4.0.0.0

    ASP.NET Core 引用外部程序包的时候,有时会出现下面的错误: The type 'Object' is defined in an assembly that is not referenc ...

  2. 【转】Django Model field reference学习总结

    Django Model field reference学习总结(一) 本文档包含所有字段选项(field options)的内部细节和Django已经提供的field types. Field 选项 ...

  3. (转) Qt 出现“undefined reference to `vtable for”原因总结

    由于Qt本身实现的机制所限,我们在使用Qt制作某些软件程序的时候,会遇到各种各样这样那样的问题,而且很多是很难,或者根本找不到原因的,即使解决了问题,如果有人问你为什么,你只能回答--不知道. 今天我 ...

  4. undefined reference to `__android_log_print'

    使用android studio 编写NDK代码时出现错误:undefined reference to `__android_log_print' 解决办法: eclipse       andro ...

  5. CentOS 6.5 编译 PHP-7 报错:undefined reference to `libiconv_open 无法编译 PHP libiconv

    ./configure --with-mysql=/backup/mysql --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zli ...

  6. Qt - 错误总结 - 在自定义类头文件中添加Q_OBJECT 编译时报错(undefined reference to ‘vtable for xxThread)

    错误提示:在添加的QThread子类头文件添加Q_OBJECT时,编译程序,出现"undefined reference to 'vtable for xxThread'"错误提示 ...

  7. Conditional project or library reference in Visual Studio

    Conditional project or library reference in Visual Studio In case you were wondering why you haven’t ...

  8. Qt经典出错信息之undefined reference to `vtable for classname

    原文链接:Qt经典出错信息之undefined reference to `vtable for classname 这个出错信息太常见了,用过Qt两个月以上的朋友基本上都能自己解决了,因为太经典了, ...

  9. OpenCASCADE6.8.0 Reference Manual Serach Problem

    OpenCASCADE6.8.0 Reference Manual Serach Problem eryar@163.com 1. Problem 有网友反映OpenCASCADE6.8.0的Refe ...

  10. SQL SERVER 2005删除维护作业报错:The DELETE statement conflicted with the REFERENCE constraint "FK_subplan_job_id"

    案例环境: 数据库版本: Microsoft SQL Server 2005 (Microsoft SQL Server 2005 - 9.00.5000.00 (X64) ) 案例介绍: 对一个数据 ...

随机推荐

  1. C 语言 clock() 函数,例:计算多项式值

    C 语言 clock() 函数,例:计算多项式值 /** * clock(): 捕捉从程序开始运行到 clock() 被调用时所耗费的时间. * 这个时间单位是 clock tick, 即" ...

  2. Vue.js 的几点总结Watchers/router key/render

    Vue.js 的几点总结,下面就是实战案例,一起来看一下. 第一招:化繁为简的Watchers 场景还原: 1 2 3 4 5 6 7 8 created(){   this.fetchPostLis ...

  3. Java项目之项目模板(登录注册)

    链接:http://pan.baidu.com/s/1hskYopm 密码:vffl

  4. 一看你就懂,超详细java中的ClassLoader详解(转)

    转载地址     http://blog.csdn.net/briblue/article/details/54973413   目录(?)[-] Class文件的认识 你还记得java环境变量吗 J ...

  5. ipad中icon与launchimage的size

    图标(AppIcon)与启动图(LaunchImage)是开发iOS应用程序必不可少的内容,但是在网络上对于这部分的内容讲解的并不详细,所以花些时间写了这篇文章,希望有需要的朋友可以随时查看 想知道A ...

  6. 二分+最小生成树【bzoj2654】: tree

    2654: tree 给你一个无向带权连通图,每条边是黑色或白色.让你求一棵最小权的恰好有need条白色边的生成树. 题目保证有解. 二分答案,然后跑最小生成树判断. 注意优先跑白色边. code: ...

  7. opencv-图片合成视频

    无论视频的合成还是分解我们都需要进行解码器或者是编码器(因为视频不是一帧一帧进行存储的,而是进行过压缩编码.) import cv2 img = cv2.imread('image1.jpg') im ...

  8. 分析mybatis和jdbc的作用,已经原理

    从jdbc的操作数据库来看:主要分为几步: 1 注冊载入JDBC驱动程序: 2 得到连接对象 Connection 3 创建 Statement对象 4 运行sql语句 5 处理结果 6 关闭资源释放 ...

  9. vue 学习一

    这个是很早之前公司要使用vue.js时候学习记在有道云笔记上的,发觉那个笔记贼多了,没办法,觉得是要换个地方存笔记了, 一vue.js的使用: 可以在页面是直接使用: <!DOCTYPE htm ...

  10. Jmeter函数引用和函数重定向【转】

    在jmeter中的[选项]中选择[函数助手对话框]---这些函数可以高速有效的帮助我们开展自动化编写与校验!!!!!! 如图: 重点!!!本章的侧重点不讲函数的具体使用,函数具体的使用与java类似, ...