Pages

Tuesday, August 21, 2012

Flyweight design pattern in java

fly weight design pattern is a structural patterns used to improve memory usage and performance. Here, instead of creating a large number of objects, we reuse the objects that are already created.

Lets say we have a MathHelper interface and has doMath method.

public interface MathHelper{
   void doMath(int a , int b);
}

Let's implement two classes that implement MathHelper.

public class Multiplier implements MathHelper{
  @override
  public void doMath(int a , int b){
      System.out.println(a*b);
  }
}


public class Adder implements MathHelper{
  @override
   public void doMath(int a , int b){
      System.out.println(a+b);
  }
}


Now we have the factory class that limits creating the objects.

public class FlyweightFactory{
 
    public FlyweightFactory(){
       Map<String,MathHelper> map = new HashMap<String,MathHelper>();
   }
    public static MathHelper getHelper(String val){
      if(map.containsKey(val))
          return map.get(val);
      if(val.equals("add"))
          map.put(val,new Adder());
     if(val.equals("multiply"))
          map.put(val,new Multiplier());
  }
}


Now the main method in the demo class is like this.
public static void main(String[] args){
   MathHelper helper = FlyweightFactory.getHelper("add")
   helper.doMath(2,3);
}

No comments:

Post a Comment