I was going through the Flyweight sample code at http://www.oodesign.com/flyweight-pattern-wargame-example-java-sourcecode.html and wondering how it really works when we assign a static instance (SOLDIER
as in the above site) to a non-static soldier instance in SoldierClient
do we really reduce the object size since each SoldierClient
will somehow hold a copy of SOLDIER
instance in each SoldierClient
object we create?
EDIT:
In the method moveSoldier()
it says
// delete soldier representation from previous location
// then render soldier representation in new location
How come this doesn't affect all the objects created in class WarGame
package flyweight;
public class SoldierImp implements Soldier {
/**
* Intrinsic State maintained by flyweight implementation
* Solider Shape ( graphical represetation)
* how to display the soldier is up to the flyweight implementation
*/
private Object soldierGraphicalRepresentation;
/**
* Note that this method accepts soldier location
* Soldier Location is Extrinsic and no reference to previous location
* or new location is maintained inside the flyweight implementation
*/
public void moveSoldier(int previousLocationX, int previousLocationY,
int newLocationX, int newLocationY) {
// delete soldier representation from previous location
// then render soldier representation in new location
}
A
SoldierClient
doesn't hold a copy ofSOLDIER
, it holds a reference toSOLDIER
, and everySoldierClient
holds a reference to the sameSOLDIER
.Answering the edit
Each soldier's location is held in
SoldierClient
instances (currentLocationX
andcurrentLocationY
properties). The code comments for those properties spell it out as well: "this state is maintained by the client" (i.e., "this state is not maintained in theSoldierImp
instance").Everything is in
moveSoldier
's parameters: there's noSoldierImp
instance state. Think of it like a static utility method. Coordinates are provided by theSoldierClient
instance; they're never stored by theSoldierImp
--just used.