Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flyweight pattern vs static fields

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

enter image description here

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?

like image 385
Tamas Pataky Avatar asked Feb 23 '13 13:02

Tamas Pataky


2 Answers

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.

like image 91
JB Nizet Avatar answered Sep 21 '22 19:09

JB Nizet


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:

  1. managing a pool of graphical representations
  2. the job of a typical 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.

like image 33
Nghia Bui Avatar answered Sep 19 '22 19:09

Nghia Bui