Factory Pattern Using Generics

The basic functionality of Factory Pattern Design to create instances as per client’s request

It could be achieved by few lines of generics collection program

Before we go through a quick example, visualize one  factory (factory class) where stuffed animals are created and delivered as per customer’s need (client object), now let’s start to implement factory

# Animal can be any animal hence it is abstract

abstract class Animal 
{
   public abstract void voice();
}

# Create more specific animal (subtype)

class Dog : Animal
{
   public override void voice()
   {
      Console.WriteLine("dog voice");
   }
}

# Create more specific animal (subtype)

class Cat : Animal
{
   public override void voice()
   {
      Console.WriteLine("cat voice");
   }
}

# Factory which creates stuff animal as per client’s requirement

class Factory
{
   public static Animal create() where T : Animal, new()
   {
      T obj = new T();
      return obj;
   }
}

# For one moment consider Program a customer it ask for cat and dog from factory

class Program
{ 
   static void Main(string[] args)
   {
      Animal cat =   Factory.create();
      cat.voice();

      Animal dog = Factory.create();
      dog.voice();
   }
}

# OUTPUT…

cat voice
dog voice
Press any key to continue . . .
Advertisements

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