How flyweight design pattern maintains different objects?

988 views Asked by At

(i found this example while reading the flyweight )
let's assume there is an object called soldier in a game and this object differs by it's location only
now my question is
if i'm to use the flyweight pattern on this object , i may ask to obtain a soldier many times during the game and i want each soldier to have it's own location.
how can i handle that?

2

There are 2 answers

0
patheros On

The flyweight design patter would be useful if all soldiers contained a bunch of shared data. For example lets say you have Soldiers and Civilians. Each has different maxHP, attackSpeed and damage but all Soldiers share these attributes. In that case you might make:

class UnitTemplate {
    String name;
    int maxHP;
    int attackSpeed;
    int damage;
}

class Unit{
    UnitTemplate template;
    int x;
    int y;
}

There would be 2 instances of UnitTemplate one for the solider type of unit and one for the civilian type of unit. There could be any number of Unit instances and each one would point to either the soldier UnitTemplate or the civilian UnitTemplate.

0
dsummersl On

Yeah, I agree with patheros...but I'd like to point out that one's incentive to use the Flyweight pattern doesn't require some additional class structure. The incentive is that by using the Flyweight pattern you minimize use of common/heavy resources.

Suppose that all Soldiers use the same graphical representation. Rather than each Soldier instantiating the graphical data (ie, some common 'heavy' aspect of your implementation), you create one 'template' object that is shared by all the soldiers.

class SharedSoldierData {
  /** UI representation, big, and common to all. */
  byte[] bitmap;
}

class Soldier {
  int x,y;

  void doMovement(SharedSoldierData extraData) {
    // In order to move, this method needs the 'UI' information (a bitmap), which must be provided.
  }
} 

// example usage:
SharedSoldierData soldierType = new SharedSoldierData(...); // setup with the soldiers bitmap
Soldier soldier1 = new Soldier();
Soldier soldier2 = new Soldier();

// modify the solider x/y locations as the game progresses...

soldier1.doMovement(soldierType); // move soldier 1
soldier2.doMovement(soldierType); // ditto for soldier 2.

You would only have one instance of the SharedSoldierData class (one instance of the heavy resource; in this case a bitmap), but you would have potentially several instances of the Soldier class. The soldier can't 'do anything' unless its provided access to the heavy resource data...