Search This Blog

Saturday, July 3, 2021

Csharp: Factory Pattern


>> Main() method also known as client side method. So the tradational approach of calling a method of a particular class is to create an object of class with the help of new keyword and then call the required method of this class. 





============================================================================== Quick Revision

Below is the final version with factory pattern implemented. 

 interface Igetdetails
    {
        void getname();
        void getfathername();
    }

    class Teacher : Igetdetails
    {
        public void getname()
        {
            Console.WriteLine("Teacher name");
        }

        public void getfathername()
        {
            Console.WriteLine("Teacher Father name");
        }

    }

    class Student : Igetdetails
    {
        public void getname()
        {
            Console.WriteLine("Student name");
        }

        public void getfathername()
        {
            Console.WriteLine("Student Father name");
        }
    }

    class factory
    {
        public static Igetdetails createobject(string type)
        {
            Igetdetails obj = null;
            if (type.ToLower() == "teacher")
            {
                obj = new Teacher();
            }
            else
            {
                obj = new Student();
            }
            return obj;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var clientobj = factory.createobject("student");
            clientobj.getfathername();

            Console.ReadKey();
        }
    }

==============================================================================

No comments:

Post a Comment