Home > DeveloperSection > Forums > Factory Method Design Pattern using C#
Ankit Singh

Total Post:341

Points:2389
Posted on    March-04-2016 11:04 PM

 C# C# 
Ratings:


 1 Reply(s)
 324  View(s)
Rate this:
We want to use  Factory Method Design Pattern in c#. How will do this please help me. 


aditya kumar Patel

Total Post:244

Points:1736
Posted on    March-04-2016 11:09 PM

In 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");

}

}

}

 


Don't want to miss updates? Please click the below button!

Follow MindStick