How To Implement Factory Design Pattern In C#

How to Implement Factory Design Pattern in C#


Please Subscribe Youtube| Like Facebook | Follow Twitter

Introduction:

In this article we will Implement Factory Design Pattern in our code. The Factory Design Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern promotes loose coupling between classes and is useful when a system needs to be independent of the object creation process.

In this post we will create an Animal interface and two classes named Cat and Dog that will implement the Animal interface. After that, we will create factory class named AnimalFactory to generate object of Cat and Dog class based on given information.

Implementation:

Step1:

Creating Animal interface.

interface Animal
{
   void Type();
}

Step2:

Creating Cat and Dog Classes implementing Animal interface.

class Cat : Animal 
{
   public void Type()
   {
     Console.WriteLine("This is Cat");
   }    
}
class Dog : Animal 
{
   public void Type()
   {
     Console.WriteLine("This is Dog");
   }    
}

Step3:

Creating AnimalFactory class to generating object based on condition.

class AnimalFactory 
{
   public Animal getAnimal(String animalType)
   {
      if (animalType == "cat")
      {
         return new Cat();
      }
      else if (animalType == "dog")
      {
         return new Dog();
      }
      else
      {
         return null;
      }      
   }
}

Usage:

Now we will use AnimalFactory to get an Animal object. We will pass information (cat or dog) to AnimalFactory to get the type of object it needs.

AnimalFactory animalFactory = new AnimalFactory();
//passing dog
Animal type1 = animalFactory.getAnimal("dog");
//it will print: This is Dog
type1.Type();

//passing cat
Animal type2 = animalFactory.getAnimal("cat");
//it will print: This is Cat
type2.Type();

Summary:

In this article we have implemented factory method using C# step by step.

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

Your email address will not be published. Required fields are marked *