Difference between Factory and Abstract Factory

The main difference between the two is Inheritance vs Composition.
Abstract Factory uses composition whereas Factory like template uses inheritance.

Abstract factory pattern can use factory method to actulay implement different types of object creation, but it is not necessary.

I would say Abstract Factory Pattern is more into design product creations and how different variants of the product would be created , it is to supply a “kit” to create product and its different variants. It may use prototype/factory method and other builder pattern inside when actualy instantiating the object.

So In Abstract Factory Pattern ,we would provide an interface of product which can be used to create its families without specifying their concrete implementations. Lets try to understand this by example.

example :

Factory Method :

public Product createProduct(int productType){

if(type=1)

return new type1Product();

else if(type=2)

return new type2Product();

return null;

}

For Abstract Factory Pattern :

//client

abstract class ProductCreator {

public Product CreateProduct(ProductFactory factory);

}

 

class ProductCreatorImpl {

public Product CreateProduct(ProductFactory factory){

return factory.CreateProduct();

}

}

 

abstract class ProductFactory{

public Product CreateProduct();

}

 

class Type1Product extends Product{

....

}

//this class would have to implement CreateProduct(), and this creation here is using Factory Method

class Type1ProductFactory extends ProductFactory{

public Product CreateProduct(){

return new Type1Product();

}

}

This answer I had posted on coderanch as well.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s