How to Implement Factory Design Pattern in C#

Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Please Subscribe Youtube| Like Facebook | Follow Twitter

Introduction:

In this article we will Implement Factory Design Pattern in our code. Factory pattern is used when we want to create an object without showing its creation logic. 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


Share Post
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Leave a Reply

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