Introduction:
This article will discuss the Simple Factory Pattern and how to use it with Abstract Factory Patter discussed in the previous article.
About Simple Factory:
A Simple Factory pattern is one that returns an instance of one of several possible classes, depending on the data provided to it. Usually all of the classes it returns have a common parent class and common methods, but each of them performs a task differently and is optimized for different kinds of data.
Simple Factory Structure:
How Simple Factory Works:
To understand how Simple Factory pattern works, have a look at the diagram above. Product is a base class for classes ProductA and ProductB . The ProductFactory class decides which of these subclasses to return, depending on the arguments you give it. On the other hand, we define a CreateProduct method to be one that passes in some value through spec parameter. The method should return some instance of the class Product. Which one it returns doesn't matter to the developer, since they all have the same methods but different implementations. How it decides which one to return is entirely up to the factory. It could be some very complex function, but it is often quite simple.
Where Simple Factory is applied:
Simple factory is applied in may places and it is widely used, but here we will show one good place of its applications.
If you got the chance to work or examine the Enterprise Library built by microsoft, you'll notice that this concept is used. For example in Data Access Application Block of the Enterprise Library, there is class named Database (The Product Class), the classes is base class for SqlDatabase & OracleDatabase classes (The ProductA & ProductB classes). Now our factory class is named DatabaseFactory (The ProductFactory class). The DatabaseFactory class has a method named CreateDatabase(string name) (CreateProduct(spec)). CreateDatabase method is responsible to create an instance of type Database, this can be SqlDatabase or OracleDatabase based on the value send in the name parameter. One this you may need to notice, is that the CreateDatabase method is static method. The developer doesn't care of which instance is returned (SqlDatabase or OracleDatabase) as long as they all have the same methods but different implementations.


RANU VISHWAKARMAPosted Mar 15, 2010, 12:38 PM
sir what is dbfactory?