Tech Kraft

Documentum, AWS, Java, Ruby on Rails, Linux, Windows, App Servers


Java: Factory Pattern

Factory Pattern is one of the most common design patterns. In this example we will create a Factory interface, and concrete classes to implement this interface.

/*
 Class: ItemType.java
 */
 public interface ItemType{
   void doSomething();
 }

Item1.java

/*
 Class: Item1.java
 */
public class Item1 implements Factory{

@Override

public void doSomething(){

  System.out.println("My Item 1.");

}

}

Item2.java

/*
 Class: Item2.java
 */
 public class Item2 implements Factory{

@Override

public void doSomething(){

  System.out.println("My Item 2.");

}

}

 

Item3.java

/*
 Class: Item3.java
 */
 public class Item3 implements Factory{

@Override

public void doSomething(){

  System.out.println("My Item 3.");

}

}

 

ItemFactory.java

/*

Class: ItemFactory.java

*/

public class ItemFactory{

  public ItemType getItem(String itemType){

     it(itemType == null) {
        return null;
      }

      if(itemType.equalsIgnoreCase("Item1")){
         return new Item1();
      }else if(itemType.equalsIgnoreCase("Item2")){
         return new Item2();
      }else if(itemType.equalsIgnoreCase("Item3")){
         return new Item3();
      }
  return null;
  }

}
FactoryPatternDemo


public class FactoryPatternDemo{

    public static void main(String[] args) {

      ItemFactory itemFactory = new ItemFactory();

      ItemType someItem1 = itemFactory.getItem("Item1");

      someItem1.doSomething();

      ItemType someItem2 = itemFactory.getItem("Item2");

      someItem2.doSomething();

      ItemType someItem3 = itemFactory.getItem("Item3");

      someItem3.doSomething();

   }

}

 



Leave a comment

About Me

Senior Software Engineer professional with over 16 years of success with multiple open source technologies and various Content Management platforms and solutions.

Proven technical abilities through numerous projects involving enterprise web application design and development, application installation, configuration and support, and workflow and collaboration system designs.

  • Ability to learn new technologies and platforms quickly and apply them to the task at hand.
  • Excellent analytical skills, and strong communication and collaboration abilities.
  • Technical emphasis in including but not limited to Java, Ruby on Rails, Documentum and Alfresco
    in both Linux and Windows based environments

Newsletter