-2

I am a student and I had this question asked in my viva voce today and I hadn't even heard about it before.

I have searched over the internet about it and I always found the results to be very confusing and hard for me to interpret and understand.

Please, can any veteran present on this community explain it to me in a simple language.

I don't want to ask for any spoonfeeding but I tried my best to search for it and just couldn't understand a thing.

Please, explain it to me in a simple language(I am good at programming, but yet I found this concept hard to understand).

Kaushal Jain
  • 139
  • 1
  • 11

2 Answers2

3

A factory method is a (usually static) method that serves as a method for creating (or better, providing) instances of a class. It's an alternative for a simple constructor, or a full-on Factory pattern.

The advantages of a factory method over a simple constructor are

  • Readability: Car newCar = Car.duplicateOf(oldCar) reveals intent far better than Car newCar = new Car(oldCar)
  • Possibility to return something not new: MonetaryAmount.valueOf(0) could return a constant always used for zero. You could also implement your own form of interning.
  • Possibility to return a different class: Person.forAge(int age) could return an instance of Adult or Child depending on the age passed in.

The advantage over a full factory pattern is that is simpler to implement and to use. You only use a factory pattern if you need interchangeable implementations.

See also http://en.wikipedia.org/wiki/Factory_method_pattern

Joeri Hendrickx
  • 16,947
  • 4
  • 41
  • 53
1

Applicability: Use the Factory Method pattern when

  • a class can't anticipate the class of objects it must create

  • a class wants its subclasses to specify the objects it creates

  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

This link will surely help you

Don Chakkappan
  • 7,397
  • 5
  • 44
  • 59