Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




Factory Pattern described with simple example

Download Attachment

Factory method is "Define an interface for creating an object, but let the subclasses decide which class to instantiate." 

In simple words we develop an abstraction that isolates the logic for determining which type of class to create.

All Concept clear with below example.wo

You go to coffee shop and Want to order coffee. There are two type of coffee

- Hot

- Cold

Suppose in menu at number one is Hot and on two is cold

Which number you will tell, that order will processed.

To solve in factory way. Will make one abstract class and two sub classes,

    public abstract class Coffee
    {
        public abstract string Title { get; }
    }

    public class Hot : Coffee
    {
        public override string Title
        {
            get { return "Hot Coffee with Suger"; }
        }
    }

    public class Cold : Coffee
    {
        public override string Title
        {
            get { return "Cold Coffee with Ice"; }
        }
    }

// In case coffee is not available

    public class NoCoffee : Coffee
    {
        public override string Title
        {
            get { return "Today no coffee.. Would you like some drink :) "; }
        }
    }
   

Now will make an inermediate which will receive input from user and will create object of relevent class.

 public static class Factory
    {
        public static Coffee GetCoffee(int i)
        {
            switch (i)
            {
                case 0:
                    return new Hot();

                case 1:
                    return new Cold();
          
                default:
                    return new NoCoffee();

            }
        }
    }


Ok All work is complete except Order

Only need to give input

static void Main(string[] args)
        {
          Console.WriteLine( Factory.GetCoffee(1).Title);
        }

It will show Hot Coffee




Share this article   |    Print    |    Article read by 5546 times
Author:
Rohit kakria
I am software developer, moderator of xpode.com
Related Articles: No related article
Related Interview Questions: No related interview question