In This Console Program I have Created an Interface and two Classes to implement the Interface.
Next, I created the factory class clsFactory, in which conditions are there to create object. In this class besically, method decides which class object to be created.
In the Main method I'm calling the Factory class.
See the below code:
using System;
namespace testDemo
{
public interface IMath
{
int GetData(int num1, int num2);
}
public class Addition : IMath
{
public int GetData(int num1, int num2)
{
int Final = num1 + num2;
return Final;
}
}
public class Subtraction : IMath
{
public int GetData(int num1, int num2)
{
int Final = num1 - num2;
return Final;
}
}
public class clsFactory
{
static public IMath CreateandGetObj(int choice)
{
IMath imath = null;
switch (choice)
{
case 1:
imath = new Addition();
break;
case 2:
imath = new Subtraction();
break;
default:
imath = new Addition();
break;
}
return imath;
}
}
public class Program
{
static void Main()
{
Console.WriteLine("What Operation you Want?");
Console.WriteLine("1: Addition");
Console.WriteLine("2: Subtraction");
Console.WriteLine("Enter you Option and press Enter: ");
string i = Console.ReadLine();
IMath ObjIntrface = null;
ObjIntrface = clsFactory.CreateandGetObj(Convert.ToInt16(i)); // 1= Add, 2= subtract
int res = ObjIntrface.GetData(4, 7);
Console.WriteLine(res);
Console.ReadLine();
}
}
See the Output: