views:

407

answers:

5

I just read Factory Method. I understand that it provides a way to delegate the instantiation to sub-classes. But I couldn't understand the possible uses in a real-world scenario.

Can anyone give one typical example showing how Factory method pattern can be used so that I can relate to what I have read.

A problem statement for which factory method pattern is the best solution would be sufficient to make it clear.

alt text

+7  A: 

A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle, you will need to modify all your code, if you haven’t written your code following factory design pattern.

In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.

Sarfraz
+1 for a proper example. Sample code for this can be found at http://davidhayden.com/blog/dave/archive/2005/04/02/923.aspx
Mahatma
@Mahatma: thanks for that link :)
Sarfraz
+1  A: 

From API I'm developing right now:

WebGalleryFactory factory = WebGalleryFactory.newInstance (WebGalleryType.PICASA);
WebAlbum album = factory.createAlbum (title, description);

In this example I use Factory Method to create Abstract Factory of a certain type (PICASA in the example).

These two patterns are often used together.

Roman
Why not instantiating PicasaWebGalleryFactory explicitly?
Rekin
+2  A: 

Zend_Db uses it in it's Zend_Db_Adapter class to allow the creation of different kinds of database objects based on database settings passed through from a configuration object.

Tobias Cohen
+1  A: 

One example from the .NET Base Class Library (BCL) is Control.CreateControlsInstance, which is is used by many other members of the (Windows Forms) Control class.

You can override this protected method to provide your own collection of controls, e.g. when you are implementing a custom control.

Mark Seemann
+1  A: 

The Wikipedia article on this explains some motivation. The Portland Pattern Repository also has information. Both of these were very high up on the list of results from a search on Google.

JUST MY correct OPINION