In my understanding the purpose of the flyweight pattern is to decrease memory footprint and increase performance by sharing common, extrinsic state. Why would anyone prefer to implement the pattern over storing the shared state in static fields?
Consider the following example: http://www.oodesign.com/flyweight-pattern-wargame-example-java-sourcecode.html
If I am right then the point in this example is to share the common state (soldierGraphicalRepresentation object) between all instances of the SoldierClient class by holding a reference to a single SoldierImp object.
Why would I hassle with implementing this design? I would be tempted to declare the SoldierClient class as follows:
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
}
}
This way all instances of the SoilderClient share a reference to the same soldierGraphicalRepresentation object and the same goal is achieved. Am I wrong?
The point of the pattern is that you can have 200 "big red" soldiers sharing the same "big red" graphical representation, 300 "small blue" soldiers sharing the same "small blue" graphical representation, etc. If you make the graphical representation static, all the soldiers will be identical.
Static fields work, no matter how many red/green/blue graphical representations you may have. The only problem with static fields is that they break Single Responsibility Principle. As you see, your SoldierClient
class has two jobs:
SoldierClient
With this design, it's very difficult to reuse one of these two jobs in another context. For example, the pool cannot be reuse for Monster
objects which also need to share graphical representations; the typical SoldierClient
cannot be used in another context which has nothing to do with a pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With