flyweight


The flyweight pattern is usfull when a application calls
for numerious instances of the same object. Instead of
creating multiple objects one object is created with
multiple references.
If the objects needed have some state/individual information
(extrinsic information) this can be moved to some other
object that is passed to the flyweight object as needed.




The flyweight abstract super class.
Notice: this class is Immutable.
-----------------------------------------------------
abstract class AbstractFlyweight{
    private String type;
    
    public AbstractFlyweight(String type){
        this.type = type;
    }

    public String getType(){return type;}
    public abstract void doIt(Object extrinsicState);
}
-----------------------------------------------------


The concrete flyweight class.
-----------------------------------------------------
class ConcreteFlyweight extends AbstractFlyweight{

    public  ConcreteFlyweight(String type){
        super(type);
    }

    public void doIt(Object extrinsicState){
        //use extrinsicState if needed.
        System.out.println("I did it");
    }
}
-----------------------------------------------------


The factory class.
This is utilizing Object Pooling. 
If the factory already has made a flyweight of the 
requested type it simple returns the one it has. 
-----------------------------------------------------
class FlyweightFactory{
    private Vector flyweightPool = new Vector();

    public AbstractFlyweight makeFlyweight(String type){
        AbstractFlyweight temp;
        for(int i=0;i<flyweightPool.size();i++){
            temp = (AbstractFlyweight)flyweightPool.get(i);
            if(temp.getType().equals(type)){
                return temp;
            }
        }  
        //there is usually multiple types.
        temp = new ConcreteFlyweight(type);
        flyweightPool.add(temp);
        return temp;
       }
}
-----------------------------------------------------


The client class.
-----------------------------------------------------
class Test{

    public static void main(String[] args){
        System.out.println("class: Test, method: main");

        FlyweightFactory flyweightFactory = new FlyweightFactory();
        String param = "state, or paramters that determine the type";
        AbstractFlyweight abstractFlyweight = flyweightFactory.makeFlyweight(param);
        String extrinsicState = "any external state  info";
        abstractFlyweight.doIt(extrinsicState);
    }
}
-----------------------------------------------------



Here is a tar with the above java classes in it. 
flyweight.tar