Friday, December 06, 2013

Flyweight Design Pattern

Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease objects count thus improving application required objects structure.
Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. We'll demonstrate this pattern by drawing 10 Rectangle  of different locations but we'll creating only 2 objects. Only 2 types are available so type property is used to check already existing Rectangle objects.


Implementation
We're going to create a Shape interface and concrete class Rectangle implementing the Shape interface. A factory class ShapeFactory is defined as a next step.
ShapeFactory have a HashMap of Rectangle having key as type of the Rectangle object. Whenever a request comes to create a rectangle of particular type to ShapeFactory. ShapeFactory checks the rectangle object in its HashMap, if object of Rectangle found, that object is returned otherwise a new object is created, stored in hashmap for future use and returned to client.
FlyWeightPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (small/big) to ShapeFactory to get the rectangle of desired rectangle  it needs.


Step 1
Create an interface.
Shape.java
public interface Shape {
   void draw();
}

Step 2
Create concrete class implementing the same interface.
Rectangle.java
public class Rectangle implements Shape {
   private String type;
   private int x;
   private int y;
   private float width;
   private float height:

   public Rectangle(String type){
      this.type = type;
   }

   public void setX(int x) {
      this.x = x;
   }

   public void setY(int y) {
      this.y = y;
   }

   

   @Override
   public void draw() {
      if(this.type.equals("small")){
this.width = 5.0f;
          this.height=3.0f;
           
}else if(this.type.equals("big")){
this.width = 25.0f;
          this.height=15.0f;
      }else{
         return;
}
      System.out.println("Rectangle: Draw() type : " + type 
         +", x : " + x +", y :" + y +");
   }
}


Step 3
Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
import java.util.HashMap;

public class ShapeFactory {
   private static final HashMap<String, Shape> rectMap = new HashMap();

   public static Shape getRectangle(String type) {
      Rectangle rectangle = (Rectangle)rectMap.get(type);

      if(rectangle == null) {
         rectangle = new Rectangle(type);
         rectMap.put(type, rectangle);
         System.out.println("Creating " + type +" Rectangle  : ");
      }
      return rectangle;
   }
}

Step 4
Use the Factory to get object of concrete class by passing an information such as type.
FlyweightPatternDemo.java
public class FlyweightPatternDemo {
   private static final String types[] = 
      { "small", "big" };
   public static void main(String[] args) {

      for(int i=0; i < 10; ++i) {
         Rectangle rectangle = 
            (Rectangle)ShapeFactory.getRectangle(types[(int)(Math.random()*types.length)]);
         rectangle.setX(getRandomX());
         rectangle.setY(getRandomY());
         rectangle.draw();
      }
   }
   
   private static int getRandomX() {
      return (int)(Math.random()*100 );
   }
   private static int getRandomY() {
      return (int)(Math.random()*100);
   }
}

Step 5
Verify the output.
Creating small Rectangle
Rectangle: Draw() type : small, x : 36, y :71
Creating big Rectangle
Rectangle: Draw() type : big, x : 27, y :27
Rectangle: Draw() type : small, x : 3, y :91
Rectangle: Draw() type : small, x : 62, y :82
Rectangle: Draw() type : big, x : 97, y :61
Rectangle: Draw() type : big, x : 86, y :12
Rectangle: Draw() type : small, x : 38, y :93
Rectangle: Draw() type : big, x : 76, y :82



No comments:

Post a Comment

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...