Pages

Showing posts with label java-rare. Show all posts
Showing posts with label java-rare. Show all posts

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);
}

Sunday, August 12, 2012

What is a java factory method ?


Java Factory Method is a creational design pattern used by java developers. what it basically does is it instantiates objects from a set of classes by considering a certain logic. That is creating an object without specifying the exact class of object that will be created. This is quite simple. Let's see how we can do this.

Say for an example we have a shape interface

public interface Shape{
      void drawShape();
}

Now lets say we have two classes that implement the interface called Triangle and Square.


public class Triangle implements Shape{

      public void drawShape(){
         System.out.println("drawing three points and joining them");
     }
}



public class Square implements Shape{

      public void drawShape(){
         System.out.println("drawing four points and joining them");
     }
}

Now lets create the ShapeFactory class that is used to instantiate a shape.

public class ShapeFactory{

    public Shape getShape(int numberOfEdges){

               if(numberOfEdges==3)
                     return new Triangle();
               if(numberOfEdges==4)
                     return new Square();
          return null;//just to make the compiler happy ;)
    }
}


Now let's see how to create a new square or a triangle. create a new class ShapeManager.

public class ShapeManager{

    public static void main(String[] args){
           ShapeFactory factory = new ShapeFactory();
           Shape triangle = factory.getShape(3);//note that the object will be a triangle since the //parameter is 3
    }
}


This is simply what happens in a factory method. You do not directly call "new"
 key word to create an instance of shape. Instead you use a factory method to get an instance.

Tuesday, July 17, 2012

Java how to invoke a static method using a string value

You can invoke a static method as below

Let's say you need to call SimpleClass.simpleMethod(int x);

Method m = SimpleClass.class.getDeclaredMethod("simpleMethod", Integer.TYPE);
m.setAccessible(true); //if security settings allow this
Object o = m.invoke(null, 20); //use null if the method is static

java invoke methods by a string name.

Let's assume that you have a string value and the method name also have the same name as the string value. If you want to invoke the the method using the
string value you can do it like this,

Object obj;//object class which the method has
String methodName = "getName" //string that you need to invoke the method.
 
THEN GET THE METHOD LIKE THIS
 
java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
  // ...
} catch (NoSuchMethodException e) {
  // ...
}
 
AFTER THAT YOU CAN INOKE IT LIKE THIS
 
try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}