An object factory is a special kind of object that has the single purpose of creating other objects. But why would you want to do this?
Typically, when we need to create an object we just call createObject() or one of the other bunch of object creation techniques. However as your applications grow you may need to do some extra work to "initialise" an object before it may be used. One example of this kind of object preparation is dependency injection, a fancy name for a technique for "getting objects to work together".
Assisting in the creation and preparation of your more complicated objects is the main purpose of an object factory, but they can also be useful in a few other ways. Factories can hiding the physical location of your objects from your application, so if you re-organise your component directory structure then the rest of your application is not affected. They can also assist in managing the number of instances of an object that are created.
Let's take a look at object factories and how you might write your own simple factory.
First up, to better understand why you might use an object factory have a read through Dependency Injection.
Then take a look at Writing your own Object Factory.
Feedback is always welcome, so if you see any problems or if something is not clear feel free to leave a comment on how these entries could be improved. Thanks.
Recent Comments