Friday, 30 June 2017

Factory Pattern Example Code in C#

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:

Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)