享元模式(Flyweight Pattern):以共享的方式高效的支持大量的细粒度对象。通过复用内存中已存在的对象,降低系统创建对象实例的性能消耗。
//@author V:jbossjf
package Chartflyweight;
import java.util.Hashtable;
public class CharactorFactory {
private Hashtable<String, FlyWeight> charactors = new Hashtable<String, FlyWeight>();
// 构造函数
public CharactorFactory() {
charactors.put("A", new FlyWeightAIml());
charactors.put("B", new FlyWeightBIml());
}
// 获得指定字符实例
public FlyWeight getCharactor(String key) {
FlyWeight charactor = (FlyWeight) charactors.get(key);
if (charactor == null) {
if (key.equals("A")) {
charactor = new FlyWeightAIml();
} else if (key.equals("B")) {
charactor = new FlyWeightBIml();
}
charactors.put(key, charactor);
}
return charactor;
}
}
package Chartflyweight;
public abstract class FlyWeight {
protected String charStr = "";
protected int fontSize;
protected abstract void operator(int fontSize);
// 显示方法
protected abstract void displayCharator();
}
package Chartflyweight;
public class FlyWeightAIml extends FlyWeight {
@Override
protected void operator(int fontSize) {
this.fontSize=fontSize;
}
public FlyWeightAIml() {
this.charStr = "A";
this.fontSize=12;
}
@Override
protected void displayCharator() {
System.out.println("字符:" + this.charStr + ",大小:" + fontSize);
}
}
package Chartflyweight;
public class FlyWeightBIml extends FlyWeight {
@Override
protected void operator(int fontSize) {
this.fontSize = fontSize;
}
public FlyWeightBIml() {
this.charStr = "B";
this.fontSize = 12;
}
@Override
protected void displayCharator() {
System.out.println("字符:" + this.charStr + ",大小:" + fontSize);
}
}
package Chartflyweight;
//如何有特别多的外部状态,则需要很多的函数,函数进行抽取
public class Clinet {
public static void main(String[] args) {
FlyWeightAIml a = new FlyWeightAIml();
FlyWeightBIml b = new FlyWeightBIml();
// 显示字符A
display(a, 12);
// 显示字符B
display(b, 14);
}
// 设置字符的大小
public static void display(FlyWeight objChar, int nSize) {
try {
System.out.println("字符:" + objChar.charStr + ",大小:" + nSize);
} catch (Exception err) {
}
}
}