在我看来,享元模式的目的是通过共享通用外部状态来减少内存占用并提高性能。为什么有人会选择实现这个模式而不是将共享状态存储在静态字段中呢?
考虑以下示例:http://www.oodesign.com/flyweight-pattern-wargame-example-java-sourcecode.html 如果我的理解是正确的,那么这个示例的重点是通过持有对单个SoldierImp对象的引用,在所有SoldierClient类实例之间共享常见状态(soldierGraphicalRepresentation对象)。
为什么要麻烦地实现这个设计?我更倾向于将SoldierClient类声明如下:
这样所有的SoilderClient实例都共享同一个soldierGraphicalRepresentation对象的引用,从而达到相同的目的。我错了吗?
考虑以下示例:http://www.oodesign.com/flyweight-pattern-wargame-example-java-sourcecode.html 如果我的理解是正确的,那么这个示例的重点是通过持有对单个SoldierImp对象的引用,在所有SoldierClient类实例之间共享常见状态(soldierGraphicalRepresentation对象)。
为什么要麻烦地实现这个设计?我更倾向于将SoldierClient类声明如下:
public class SoldierClient implements Soldier
{
protected static Object soldierGraphicalRepresentation;
private int currentLocationX;
private int currentLocationY;
static SoldierImp()
{
soldierGraphicalRepresentation = LoadGraphicalRepresentation();
}
public void moveSoldier(int previousLocationX, int previousLocationY, int newLocationX, int newLocationY) {
// do stuff with the graphical representation
}
}
这样所有的SoilderClient实例都共享同一个soldierGraphicalRepresentation对象的引用,从而达到相同的目的。我错了吗?