Factory Method Design Pattern using C#
1944
04-Mar-2016
We want to use Factory Method Design Pattern in c#. How will do this please help me.
Anonymous User
04-Mar-2016In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
using System;
using System.Linq;
namespace ConsoleDemo
{
public class Program
{
static void Main()
{
Factory[] objFactories = new Factory[2];
objFactories[0] = new concreteFactoryforEmployee();
objFactories[1] = new concreteFactoryforFounder();
foreach (Factory objFactory in objFactories)
{
DetailsMaster objProduct = objFactory.GetDetails();
objProduct.GetDetails();
}
Console.ReadLine();
}
}
abstract class Factory
{
public abstract DetailsMaster GetDetails(); //Factory Method Declaration
}
class concreteFactoryforEmployee : Factory
{
public override DetailsMaster GetDetails() //Factory Method Implementation
{
return new Employee();
}
}
class concreteFactoryforFounder : Factory
{
public override DetailsMaster GetDetails() //Factory Method Implementation
{
return new Founder();
}
}
interface DetailsMaster
{
void GetDetails();
}
class Employee : DetailsMaster
{
public void GetDetails()
{
Console.WriteLine("Emplyee Details");
Console.WriteLine("======================================");
Console.WriteLine("Name : Rahul");
Console.WriteLine("Join Date : 03/03/206");
Console.WriteLine("designation : Software Developer");
Console.WriteLine("======================================");
}
}
class Founder : DetailsMaster
{
public void GetDetails()
{
Console.WriteLine("Company Details");
Console.WriteLine("======================================");
Console.WriteLine("Name : Jan Singh");
Console.WriteLine("Company Name : ItechWays");
}
}
}