Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Abstract Factory Pattern using Java
01-22-2010, 02:16 PM
Post: #1
Abstract Factory Pattern using Java
Factory Pattern is a widely used efficient pattern that eliminates the need of Constructing objects in the client code. Instead the Factory creates and delivers objects as required by the client. This method eliminates the need to instantiate (use the new keyword) with a client code.

A small example demonstrates this pattern.
Beverage.java
Code:
public interface Beverage {
    void addSugar();
    void stir();
}

Tea.java
Code:
public class Tea implements Beverage {
    public void addSugar(){
        System.out.println("Sugar Added to Tea");
    }

    public void stir(){
        System.out.println("Tea stirred");
    }
}

Coffee.java
Code:
public class Coffee implements Beverage {
    public void addSugar(){
        System.out.println("Sugar Added to Coffee");
    }

    public void stir(){
        System.out.println("Coffee stirred");
    }
}
BeverageFactory.java
Code:
public abstract class BeverageFactory {
    public static final int COFFEE = 1;
    public static final int TEA = COFFEE + 1;

    public static Beverage getBeverage(int whichBeverage){
        switch(whichBeverage){
            case 1 : return new Coffee();
            case 2 : return new Tea();
            default : return null;
        }
    }

    
}

FactoryTest.java
Code:
public class FactoryTest {
    public static void main(String[] args){
        Beverage tea = BeverageFactory.getBeverage(BeverageFactory.TEA);
        
        tea.addSugar();    
        tea.stir();

        Beverage coffee = BeverageFactory.getBeverage(BeverageFactory.COFFEE);        

        coffee.addSugar();
        coffee.stir();
    }
}

Shazin Sadakath
Bsc (Hons) Software Engineering (UG)
SCJP 1.5
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


Contact Us | Coder Passion | Return to Top | Return to Content | Lite (Archive) Mode | RSS Syndication | Site Map