Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Factory Pattern

0.00/5 (No votes)
17 Jun 2012 1  
Factory method is Define an interface for creating an object, but let the subclasses decide which class to instantiate. In simple words we

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

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

For source code, visit on below url:


http://www.xpode.com/ShowArticle.aspx?ArticleId=610

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here