Click here to Skip to main content
15,887,135 members
Articles / Programming Languages / C#

Factory Method C#

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
21 Apr 2018CPOL1 min read 9.7K   6   6
Factory method C#

Factory Method belongs to Creational Patterns and it is useful when you have a set of classes performing a similar operation, but the exact class to be used to get the job done is dependent on some logic or condition.

As the name suggests, the factory method pattern defines a way to create an object. And the subclasses decide which class to instantiate. How do these subclasses decide which class to instantiate?
This is quite application specific, and may involve some programmatic logic or configuration setting.

Problem

Suppose you design an application to render a specific type of chart and your library has to receive a set of records to render, but you don't know what type of chart you are going to receive, as a consequence, you don´t know what type of chart you are going to render, how do you deal with it ?

Design

Image 1

Solution

Factory Method comes to the rescue with this type of requirement.

Steps

The first that you must create is an interface IChart that defines GenerateChart() method.

The second is creating the class that will implement this Interface IChart: BarChart and PieChart.

After that, create an Interface called IChartCreator which is responsible for returning the proper Chart according to a specific TypeOfChart.

Code in Console

C#
class Program
    {
        static void Main(string[] args)
        {
            ChartCreator chartCreator = new ChartCreator();
            for (int i = 1; i <= 2; i++)
            {
                var chart = chartCreator.GetChart(i);
                Console.WriteLine("Where id = {0}, chart = {1} ", i, chart.GenerateChart());
            }
            Console.ReadKey();
        }
    }

    public interface IChart
    {
        string GenerateChart();
    }

    public class BarChart : IChart
    {
        public string GenerateChart()
        {
            return "Generating BarChart.";
        }
    }
    public class PieChart : IChart
    {
        public string GenerateChart()
        {
            return "Generating PieChart.";
        }
    }

    public interface IChartCreator
    {
        IChart GetChart(int id);
    }

    public class ChartCreator : IChartCreator
    {
        public IChart GetChart(int id)
        {
            IChart chart = null;

            switch (id)
            {
                case (int)ChartType.BarChart:
                    chart = new BarChart();
                    break;
                case (int)ChartType.PieChart:
                    chart = new PieChart();
                    break;
            }
            return chart;
        }
    }

    public enum ChartType
    {
        BarChart = 1,
        PieChart = 2
    }

Conclusion

Factory classes are often implemented because they allow the project to follow the SOLID principles more closely. In particular, the interface segregation and dependency inversion principles.

Factory method is often used in the next situations:

  • A class cannot anticipate the type of objects it needs to create beforehand.
  • A class requires its subclasses to specify the objects it creates.
  • You want to localize the logic to instantiate a complex object.

Code Running in .NET Fiddle

Find this code running here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Uruguay Uruguay
I am Software Developer with a passion for technology with strong backend (PHP, MySQL, PostgreSQL and SQL Server) and frontend (HTML5, CSS3, AngularJs and KnockOutJs) experience. I combine my education with expertise in CSS3, HTML5, Javascript to build creative and effective websites and applications.

If you wish to contact me then please do so on ricardojavister@gmail.com or feel free to skype me on
ricardo-torres-torres.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Andy Peralta26-Apr-18 8:32
Andy Peralta26-Apr-18 8:32 
Questiondid you consider using Activator CreateInstance<T> ? Pin
BillWoodruff23-Apr-18 5:18
professionalBillWoodruff23-Apr-18 5:18 
QuestionSingle Responsibility Pin
George Swan21-Apr-18 22:35
mveGeorge Swan21-Apr-18 22:35 
AnswerRe: Single Responsibility Pin
BillWoodruff23-Apr-18 18:35
professionalBillWoodruff23-Apr-18 18:35 
GeneralRe: Single Responsibility Pin
George Swan23-Apr-18 22:28
mveGeorge Swan23-Apr-18 22:28 
Thanks, Bill. My understanding is that, if you new-up a class inside a method, the method becomes dependent upon that class and you run the risk that a gang of four will come along and arrest you.

GeneralRe: Single Responsibility Pin
BillWoodruff24-Apr-18 19:03
professionalBillWoodruff24-Apr-18 19:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.