源自:http://www.blogjava.net/flustar/archive/2008/01/26/flyw.html
FlyWeight享元模式:
运用共享技术有效地支持大量细粒度对象。
也就是说在一个系统中如果有多个相同的对象,那么只共享一份就可以了,不必每个都去实例化一个对象。在Flyweight模式中,由于要产生各种各样的对象,所以在Flyweight(享元)模式中常出现Factory模式。Flyweight的内部状态是用来共享的,Flyweight factory负责维护一个对象存储池(Flyweight Pool)来存放内部状态的对象。Flyweight模式是一个提高程序效率和性能的模式,会大大加快程序的运行速度。
例子:
public abstract class Character {
protected char symbol;
protected int width;
protected int height;
protected int ascent;
protected int descent;
protected int pointSize;
public abstract void Display(int pointSize);
}
public class CharacterA extends Character {
public CharacterA() {
this.symbol = 'A';
this.height = 100;
this.width = 120;
this.ascent = 70;
this.descent = 0;
}
public void Display(int pointSize) {
this.pointSize = pointSize;
System.out.println(this.symbol + " (pointsize " + this.pointSize + ")");
}
}
public class CharacterB extends Character {
public CharacterB() {
this.symbol = 'B';
this.height = 100;
this.width = 140;
this.ascent = 72;
this.descent = 0;
}
public void Display(int pointSize) {
this.pointSize = pointSize;
System.out.println(this.symbol + " (pointsize " + this.pointSize + ")");
}
}
//C, D, E, etc.
public class CharacterZ extends Character {
public CharacterZ() {
this.symbol = 'Z';
this.height = 100;
this.width = 100;
this.ascent = 68;
this.descent = 0;
}
public void Display(int pointSize) {
this.pointSize = pointSize;
System.out.println(this.symbol + " (pointsize " + this.pointSize + ")");
}
}
public class CharacterFactory {
private Hashtable characters = new Hashtable();
public Character GetCharacter(char key) {
// Uses "lazy initialization"
Character character = (Character) characters.get(key);
if (character == null) {
switch (key) {
case 'A':
character = new CharacterA();
break;
case 'B':
character = new CharacterB();
break;
//
case 'Z':
character = new CharacterZ();
break;
}
characters.put(key, character);
}
return character;
}
}
public class Client {
public static void main(String[] args) {
String document = "AAZZBBZB";
char[] chars = document.toCharArray();
CharacterFactory f = new CharacterFactory();
int pointSize = 10;
for (char c : chars) {
pointSize++;
Character character = f.GetCharacter(c);
character.Display(pointSize);
}
}
}