Factory Method Pattern

The Factory Method Pattern is one of the Design Patterns discussed in the Gang Of Four book of the same name.

(Page 107)

www.dofactory.com

Be careful: An Operation method has to call Factory Method! The illustration above is confusing.

It allows classes to defer object creation to a separate method (a Factory Method). This would be an additional method on existing classes in a hierarchy.

Also called the Virtual Constructor; this is because in a statically-typed language (like Cee Plus Plus) the object returned is of the type indicated by the method signature, or a subtype. Compare this with a standard constructor, which always gives you a Foo and never a subtype of Foo.


The factory method ensures an interface which returns the product type depending on the implementation of the creator class..It's similar to Abstract Factory in that the methods of the Abstract factory can be implemented as factory methods.The main difference is that while abstract factory deals with a family of products,the factory method is only worried about a single product.

I see that differently and agree with the description in Abstract Factory Vs Factory Method -- Ilja Preuss


Factory methods are sometimes used in place of constructors for any of several reasons:

Some languages (such as Java) do not allow constructors to have useful names

Some languages (such as Java) do not allow constructors to have different names (which may be necessary if you want to use the same method signature for two constructors)

To allow the same instance to be reused instead of recreated each time it is needed (see Flyweight Pattern)


Links:


See original on c2.com