运用共享技术有效地支持大量细粒度的对象。
1.一次性实现一个算法的不变的部分,并将可变的行为留给子类来实现。
2.各子类中公共的行为应被提取出来并集中到一个公共父类中以避免代码重复。 首先识别现有代码中的不同之处,并且将不同之处分离为新的操作。 最后,用一个调用这些新的操作的模板方法来替换这些不同的代码。
3.控制子类扩展。
例子;
享元接口:
public interface Flyweight {
void action(int arg);
}
享元接口的实现类:
public class FlyweightImpl implements Flyweight{
@Override
public void action(int arg) {
System.out.println("参数值: " + arg);
}
}
产生精度对象的工厂类:
public class FlyweightFactory {
private static Map<String,Flyweight> flyweightsMap = new HashMap<String,Flyweight>();
public FlyweightFactory(String arg) {
System.out.println("-----------------");
flyweightsMap.put(arg, new FlyweightImpl());
}
public static Flyweight getFlyweight(String key) {
if (flyweightsMap.get(key) == null) {
flyweightsMap.put(key, new FlyweightImpl());
}
return (Flyweight) flyweightsMap.get(key);
}
public static int getSize() {
return flyweightsMap.size();
}
}
测试类:
public class Test {
public static void main(String[] args) {
Flyweight fly1 = FlyweightFactory.getFlyweight("a");
fly1.action(1);
Flyweight fly2 = FlyweightFactory.getFlyweight("a");
System.out.println(fly1 == fly2);
Flyweight fly3 = FlyweightFactory.getFlyweight("c");
fly3.action(3);
Flyweight fly4 = FlyweightFactory.getFlyweight("d");
fly4.action(4);
Flyweight fly5 = FlyweightFactory.getFlyweight("e");
fly5.action(5);
System.out.println(FlyweightFactory.getSize());
}
}