This video is about Factory Design Pattern in C# with example. Here you will learn what is design pattern, what is factory design pattern - its Creational design Pattern, I will show you simple example without its implementation that means traditional approach and then I will show you implementing the same code using Factory design pattern.
Traditional way Code implementation without Factory Design Pattern:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WithoutFactory
{
class Program
{
static void Main(string[] args)
{
Igym obj = null;
Console.WriteLine("Which Membership you want?");
string type = Console.ReadLine();
if (type == "monthly")
{
obj = new Monthly();
}
else if (type == "yearly")
{
obj = new Yearly();
}
Console.WriteLine(obj.getcharges());
Console.ReadLine();
}
}
public interface Igym
{
int getcharges();
}
public class Monthly : Igym
{
public int getcharges()
{
return 2000;
}
}
public class Yearly : Igym
{
public int getcharges()
{
return 8000;
}
}
}
Code implementation with Factory Design Pattern:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WithFactory
{
class Program
{
static void Main(string[] args)
{
MembershipFactory obj = new ConcreteMembership();
Console.WriteLine("which membership charges you want?");
string type = Console.ReadLine();
Igym instance = obj.GetGymMembershipType(type);
Console.WriteLine(instance.getcharges());
Console.ReadLine();
}
}
public interface Igym
{
int getcharges();
}
public class Monthly : Igym
{
public int getcharges()
{
return 2000;
}
}
public class Yearly : Igym
{
public int getcharges()
{
return 8000;
}
}
public abstract class MembershipFactory //Factory class - Creator
{
public abstract Igym GetGymMembershipType(string type);
}
public class ConcreteMembership : MembershipFactory //Concrete Creator
{
public override Igym GetGymMembershipType(string type)
{
switch (type)
{
case "monthly":
return new Monthly();
case "yearly":
return new Yearly();
default:
throw new ApplicationException(string.Format("membership'{0}' not available", type));
}
}
}
}
Here you saw the difference in traditional way of code implementation and implementing factory design pattern- Factory Design Pattern in C# with example
0 comments:
Post a Comment