定义
In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory usage 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 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. —Wikipedia
- share
- graphical representation of characters in a word processor
- string interning
结构
结合Composite
例子
package com.mashibing.dp.flyweight;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
class Bullet{
public UUID id = UUID.randomUUID();
boolean living = true;
@Override
public String toString() {
return "Bullet{" +
"id=" + id +
'}';
}
}
public class BulletPool {
List<Bullet> bullets = new ArrayList<>();
{
for(int i=0; i<5; i++) bullets.add(new Bullet());
}
public Bullet getBullet() {
for(int i=0; i<bullets.size(); i++) {
Bullet b = bullets.get(i);
//返回池中living为false的子弹
if(!b.living) return b;
}
return new Bullet();
}
public static void main(String[] args) {
BulletPool bp = new BulletPool();
for(int i=0; i<10; i++) {
Bullet b = bp.getBullet();
System.out.println(b);
}
}
}
String intern()
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s3 == s4);
System.out.println(s3.intern() == s1);
System.out.println(s3.intern() == s4.intern());
}
总结
- 池化
- 共享内存