Abstract Factory Pattern
The Abstract Factory Pattern consists of an AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct and Client. We code against AbstractFactory and AbstractProduct and let the implementation to others to define ConcreteFactory and ConcreteProduct

IFoodFactory.java(AbstractFactory)

public interface IFoodFactory {
	public IFood prepareFood();
}

IFood.java(AbstractProduct)

public interface IFood {
	public void serveFood();
}

ItalianFoodFactory.java(ConcreteFactory)

public class ItalianFoodFactory implements IFoodFactory{
	@Override
	public IFood prepareFood() {
		return new ItalianFood();
	}
}

ChineseFoodFactory.java(ConcreteFactory)

public class ChineseFoodFactory implements IFoodFactory{
	@Override
	public IFood prepareFood() {
		return new ChineseFood();
	}
}

ItalianFood.java(ConcreteProduct )

public class ItalianFood implements IFood{
	@Override
	public void serveFood() {
	  System.out.println("Pepperoni Pizza by Sam");		
	}
}

ChineseFood.java(ConcreteProduct )

public class ChineseFood implements IFood{
	@Override
	public void serveFood() {
		System.out.println("Snake Soup by Bruce");;
	}		
}

TasteFood.java(Client)

public class TasteFood {
	public static void main(String[] args) {
		IFoodFactory objFoodFactory = new ChineseFoodFactory();
		IFood objFood = objFoodFactory.prepareFood();		
		objFood.serveFood();
	}
}

Output

Snake Soup by Bruce

With the Factory pattern, you produce instances of implementations (ChineseFood, ItalianFood, ThaiFood, etc.) of a particular interface — say, IFood.
With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFoodFactory or an IJuiceFactory, without requiring your warehouse to know anything about Food or Juices.Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

Factory Pattern Abstract Factory pattern
Factory Method creates objects through inheritance Abstract Factory creates objects through composition
Factory Method pattern is responsible for creating products that belong to one family Abstract Factory pattern deals with multiple families of products i.e. Food, Juice, Dessert
Factory Method uses interfaces and abstract classes to decouple the client from the generator class and the resulting products Abstract Factory has a generator that is a container for several factory methods, along with interfaces decoupling the client from the generator and the products

Download example of Abstract Factory pattern from here

Comments are closed.