Quantcast
Viewing latest article 1
Browse Latest Browse All 5

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.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 1
Browse Latest Browse All 5

Trending Articles