Thursday, December 24, 2009

How to use Factory Method?

Overview:

The factory method pattern is an object-oriented design pattern. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of product that will be created. More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.


How to create objects runtime?
  1. Write one Interface which has one method called myMethod().
  2. Write some set of Classes which implements this interface.
  3. Write one Class which has one static method which would return different objects based on the argument pass to that method.
Code Snap-shot:
  1. Interface code.

    1.1 myinterface.java
    public interface myinterface {
    public void myMethod();
    }
  2. Some set of Classes.

    2.1 a.java
    public class a implements myinterface {
    public a() {
    System.out.println("I am a...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from a...");
    }
    }
    2.2 b.java
    public class b implements myinterface {
    public b() {
    System.out.println("I am b...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from b...");
    }
    }
    2.3 b1.java
    public class b1 extends b {
    public b1() {
    System.out.println("I am b1...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from b1...");
    }
    }
    2.4 b2.java
    public class b2 extends b {
    public b2() {
    System.out.println("I am b2...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from b2...");
    }
    }

  3. Class which would return object based on the argument pass.

    3.1 test.java
    public class test {
    public test() {
    System.out.println("I am test class...");
    }

    public static myinterface getMyInterface(String ftpType) {
    try {
    if (ftpType.equals("doc")) {
    return (myinterface)Class.forName("a").newInstance();
    } else if (ftpType.equals("html")) {
    return (myinterface)Class.forName("b").newInstance();
    } else if (ftpType.equals("txt")) {
    return (myinterface)Class.forName("b1").newInstance();
    } else if (ftpType.equals("xml")) {
    return (myinterface)Class.forName("b2").newInstance();
    } else {
    return null;
    }
    } catch (Exception e) {
    System.out.println(e);
    return null;
    }
    }

    public static void main (String a[]) {
    myinterface m = test.getMyInterface("txt");
    m.myMethod();
    }
    }

Try this and happy blogging & reading. Any comment pls....

No comments:

Post a Comment