Monday, May 14, 2012

Factory Method Pattern


Introduction

Suppose we have a super class (abstract class or interface) and any number of sub classes. Based on some parameters we have to return an object of any sub class without knowing the logic inside. So in this case Factory Method Pattern can be used.

Example

By assuming you are familiar with the playing cards, I'm going to illustrate the example using playing cads. So you might know in the playing cards there are 4 kinds of kings. So lets create an interface name is King and 4 classes for 4 kinds of kings.  Lets assume passing some parameters ("C", "D", "H", "S") we want to get the suit of the object. Following are the created classes.

King.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public interface King {
 
 public String getSuit();

}

Club.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Club implements King {

 @Override
 public String getSuit() {
  return "Club";
 }

}

Diamond.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Diamond implements King {

 @Override
 public String getSuit() {
  return "Diamond";
 }
 
}

Heart.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Heart implements King {

 @Override
 public String getSuit() {
  return "Heart";
 }
 
}

Spade.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Spade implements King {

 @Override
 public String getSuit() {
  return "Spade";
 }
 
}

So far so good. Now we want the factory class, passing some parameter and get the instance of King. Following is the factory class.

Factory.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Factory {

 public King getKing(String key) {
  if ("C".equals(key)) {
   return new Club();
  } else if ("D".equals(key)) {
   return new Diamond();
  } else if ("H".equals(key)) {
   return new Heart();
  } else if ("S".equals(key)) {
   return new Spade();
  } else {
   throw new RuntimeException("No king found for the key : " + key);
  }
 }
 
}

If you wish to test this pattern I created a main class for you.

Main.java

package com.blog.patterns.factorymethod;

/**
 * @author uditha
 */
public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Factory factory = new Factory();
  King king = factory.getKing("C");
  System.out.println(king.getSuit());
  king = factory.getKing("D");
  System.out.println(king.getSuit());
  king = factory.getKing("H");
  System.out.println(king.getSuit());
  king = factory.getKing("S");
  System.out.println(king.getSuit());
  king = factory.getKing("K");
  System.out.println(king.getSuit());
 }

}

2 comments:

  1. Interesting way to use the factory method pattern. Thanks for simple code snippets.

    ReplyDelete