Web
Analytics
factory pattern c# real world example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

WHY FACTORY:

  • Initially an object is created with the “new” operator. That basic mechanism of object creation could result in design problems or added complexity to the design. On each Object creation we must use the new keyword. The Factory helps you to reduce this practice and use the common interface to create an object.

What is Factory

▸The Factory Pattern is a Creational Pattern that simplifies object creation. You need not worry about the object creation; you just need to supply an appropriate parameter and factory to provide you a product as needed.

▸Creating objects without exposing the instantiation logic to the client

▸Referring to the newly created objects through a common interface





 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FactoryPatternEx1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Enter Your Object Type");
            string type = Console.ReadLine();
           I1 obj= CreateObj.getobject(type);
            Console.WriteLine(obj.getfname());
            Console.ReadLine();
        }
    }
    class CreateObj
    {
        public static I1 getobject(string typeofobj)
        {
            I1 obj = null;
            if(typeofobj.ToLower()=="student")
            {
                obj = new Student();
            }
            else
            {
                obj = new Teacher();
            }
            return obj;

        }
    }


    interface I1
    {
        string getname();
        string getfname();
    }
    class Teacher : I1
    {
        public string getname()
        {
            return "Techer Name";
        }
        public string getfname()
        {
            return "Techer Father Name";
        }
    }
    class Student : I1
    {
        public string getname()
        {
            return "Student Name";
        }
        public string getfname()
        {
            return "Student Father Name";
        }
    }
}