Taken from wikipedia:
In object-oriented computer
programming, a factory is an object
for creating other objects. It is an
abstraction of a constructor, and can
be used to implement various
allocation schemes.
Could anyone please explain when a factory class is required or beneficial?
I am currently working on a project where I have a class and use the constructor to initialize an object (duh!) but it can fail and not initialize at all. I have a Success property to check if it was created properly. Is this a good example for when a factory class should be implemented? This way the Create() method can return null and I can get rid of the Success property. Do I have the right idea?
The textbook example for a Factory situation is when you have an interface and several implementations, but you don’t want to expose the implementations. You implement a factory (method or class) that produces instances of different implementations based on the parameters you pass it; however, since it returns them by the interface type, the caller will not be burdened with implementation details.
Real-world example: Suppose you have defined an interface for a stream reader, and implementations to read from a local file, a network resource, and stdin. You then write a factory method that takes a single parameter (the URI), and returns a suitable reader. The caller doesn’t need to know about implementation details. The best part is, when you decide you want to support another input method, say, data: URIs, you just add another implementation and add it to the factory – you won’t need to change anything in the calling code.