Give an example of Factory Pattern

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 810
using System;

namespace FactoryPattern
{
public class ExampleWithoutStructureMap
{
Factory f = new Factory();
public void CallMe()
{
f.FactoryMethod("dog");
}
}

public interface ISpeak
{
void Speak();
}

class Cat : ISpeak
{
public void Speak()
{
Console.WriteLine("Cat says Meo");
}
}

class Dog : ISpeak
{
public void Speak()
{
Console.WriteLine("Dog barks");
}
}

class Factory
{
/// <summary>
/// Decides which class to instantiate.
/// </summary>
public ISpeak FactoryMethod(string name)
{
ISpeak instance = null;
switch (name)
{
case "dog":
instance = new Dog();
instance.Speak();
break;

case "cat":
instance = new Cat();
instance.Speak();
break;
}
return instance;
}
}
}

Comments or Responses

Login to post response