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. 类的继承与super()的意义以即如何写一个正确的异常类

    这些东西都是我看了许多名师课程和自己研究的成果,严禁转载,这里指出了如何正确的自己定义一个异常类并看一看sun写的java的源代码话题一:子类的构造器执行是否一定会伴随着父类的构造执行? 1.this ...

  2. Java从入门到放弃——03.循环和判断

    本文目标 选择结构:if,switch 循环结构:for , foreach ,while,do while 跳出语句:break,continue 1.选择结构 if: if(判断语句){  } s ...

  3. Apache 性能调优-参考篇

    1 内存     适当选用适合大小的内存,保证谷峰负载时,有足够的内存使用 2 使用ab测试apache性能 ab -n 1000 -c 10 http://www.test.com 使用ab的缺点: ...

  4. web安全-接入层注入

    web安全-接入层注入 1.关系型数据库 mysql 存放结构化数据 高效操作大量数据 方便处理数据之间的关联关系 2.SQL注入 select * from table where id=${id} ...

  5. Java基础笔记(十七)——继承(续)final

    final  最终的 修饰类,此类不能被继承.final与访问修饰符public位置随意,在class前即可.public final class A{ } 修饰方法,此方法不能被子类重写,但可以被子 ...

  6. zookeeper分布式锁简单实现(JavaApi)

    1.创建会话连接 package com.karat.cn.zookeeperAchieveLock.javaapilock; import org.apache.zookeeper.WatchedE ...

  7. Bootstrap FileInput 上传 中文 API 整理

    Bootstrap FileInput 上传  中文 API 整理 上传插件有很多 但是公司用的就是 Bootstrap FileInput 自己就看了看  会用就行 自己都不知道每个值是干嘛用的就问 ...

  8. CRF++使用步骤

    1.将CRF++文件的压缩包解压后添加到java的工程目录下 2.使用前必须生成train.data和test.data 文件并放到crf_learn.exe的同级目录下 3.cmd进入目标位置,其中 ...

  9. 毕业设计 python opencv实现车牌识别 矩形矫正

    主要代码参考https://blog.csdn.net/wzh191920/article/details/79589506 GitHub:https://github.com/yinghualuow ...

  10. form组件之modelForm

    modelForm的使用及参数设置 从modelForm这个名字就能看出来,这个form是和模型类model有知己诶关联的,还是以数和出版社的模型来说明: models.py(模型) from dja ...