Home > C#, Design Pattern, Programming > Factory Method

Factory Method

Frequency of Use
High

Intent
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Structure

Factory Method

Factory Method

Applicability
Use the Factory Method pattern when:

  • a class can’t anticipate the class of objects it must create.
  • a class wants its subclasses to specify the objects it creates.
  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

Code Implementation (C#)

using System;

namespace FactoryMethod
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Creator[] creators = new Creator[2];
            creators[0] = new ConcreteCreatorA();
            creators[1] = new ConcreteCreatorB();

            foreach(Creator creator in creators)
            {
                Product product = creator.FactoryMethod();
                Console.WriteLine("Created: " + product.GetType().Name);
            }

            Console.ReadKey();
        }
    }

    abstract class Creator
    {
        public abstract Product FactoryMethod();
    }

    class ConcreteCreatorA : Creator
    {
        public override Product FactoryMethod()
        {
            return new ProductA();
        }
    }

    class ConcreteCreatorB : Creator
    {
        public override Product FactoryMethod()
        {
            return new ProductB();
        }
    }

    abstract class Product
    {

    }

    class ProductA : Product
    {

    }

    class ProductB : Product
    {

    }

}

Output Code

Created: ProductA
Created: ProductB

 

Advertisements
Categories: C#, Design Pattern, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: