Saturday, February 11, 2012

Factory Method implementation in C#

 Factory Method

Factory Method is a widely used mechanism for creating instances of classes in any object oriented programming language. The Factory Method abstracts the Creation of objects from the consumer.It also provides a single place where objects can be created.I supplies the desired objects hiding the complexity of creation for the consumers

Advantages of Factory Method

1. Hides the Complexity of Creation from the Consumer.


2. Ensures The object creation logic to be in single place


3. Helps customise creation without disturbing the Consumer logic


4.brings in logical Seperation between creation and usage


I have used a simple CarFactory example to demonstrate the same .The Factory manufactures swift cars of 2 types basic and Featured with 3 different colors black,blue and Red.


Steps for implementing the Factory Method

1.Create an abstract class Swift Car with an attribute color and a method CaliculatePrice as the price differs for different models


















2. Create 2 derived classes For Basic Swift Car and Featured Swift Car



































3. Define Enumerations which describe the Car types and Car Colors


















4. Create a Static Class with a Static Method which Returns the Car of Desired Type
Note:
it is very important to keep the abstract base class Swift car as a Return Type.



















5. Design a Client to Consume the Car from the Swift Car Factory.






Finally it can be observed that creation logic is unknown to the client and Since the factory takes care of the creation .the Factory logic can be further customised or changed easily.

No comments: