Search This Blog

2009-06-28

Implementation of factory Pattern

What is a Factory Pattern :Factory Pattern creates an instance of several derived classes.

using System;
using System.Collections.Generic;
using System.Text;

namespace FactoryPattern
{
interface IBase
{
void DoIt();
}
class Derived1:IBase
{
public void DoIt()
{
Console.WriteLine("Derived1 Method is called");
}
}
class Derived2:IBase
{
public void DoIt()
{
Console.WriteLine("Derived2 Method is called");
}
}
class Factory
{
public IBase getObject(int type)
{
IBase objIBase = null;
switch (type)
{
case 1:
objIBase = new Derived1();
break;
case 2:
objIBase = new Derived2();
break;
}
return objIBase;
}
}
class Program
{
static void Main(string[] args)
{
Factory objFactory = new Factory();
IBase objIbase = objFactory.getObject(1);
objIbase.DoIt();
Console.ReadLine();
}
}
}

Output:


Diagram/Description

No comments: