《图解设计模式》笔记(九)避免浪费
二十、Flyweight模式:共享对象,避免浪费
如果都用new来创建对象,将消耗大量内存。
Flyweight模式:通过尽量共享实例来避免new出实例
尽量共用已经存在的实例,这就是Flyweight模式的核心内容。
示例中,这样拼出来的叫“大型字符”
示例程序类图
big0.txt
对应的还有big1.txt
至big9.txt
,以及big-.txt
....######......
..##......##....
..##......##....
..##......##....
..##......##....
..##......##....
....######......
................
BigChar
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BigChar {
// 字符名字
private char charname;
// 大型字符对应的字符串(由'#' '.' '\n'组成)
private String fontdata;
// 构造函数
public BigChar(char charname) {
this.charname = charname;
try {
BufferedReader reader = new BufferedReader(
new FileReader("big" + charname + ".txt")
);
String line;
StringBuffer buf = new StringBuffer();
while ((line = reader.readLine()) != null) {
buf.append(line);
buf.append("\n");
}
reader.close();
this.fontdata = buf.toString();
} catch (IOException e) {
this.fontdata = charname + "?";
}
}
// 显示大型字符
public void print() {
System.out.print(fontdata);
}
}
BigCharFactory
import java.util.HashMap;
public class BigCharFactory {
// 管理已经生成的BigChar的实例
private HashMap pool = new HashMap();
// Singleton模式
private static BigCharFactory singleton = new BigCharFactory();
// 构造函数
private BigCharFactory() {
}
// 获取唯一的实例
public static BigCharFactory getInstance() {
return singleton;
}
// 生成(共享)BigChar类的实例。这里是本模式的核心方法
public synchronized BigChar getBigChar(char charname) {
// 首先会通过pool.get()方法查找,是否存在接收到的字符(charname)所对应的BigChar类的实例。
BigChar bc = (BigChar)pool.get("" + charname);
if (bc == null) {
// 若为null,则目前还没有创建该实例,于是通过new BigChar(charname);来生成实例,
bc = new BigChar