Thursday 2 March 2023

Factory Pattern with example

The Factory pattern is used to create objects without specifying the exact class of object that will be created. This is useful when you want to create objects in a flexible and extensible way.

Here's an example implementation of the Factory pattern in C#:


public interface IAnimal
{
    void Speak();
}

public class Dog : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Woof!");
    }
}

public class Cat : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Meow!");
    }
}

public class AnimalFactory
{
    public IAnimal CreateAnimal(string type)
    {
        switch (type)
        {
            case "dog":
                return new Dog();
            case "cat":
                return new Cat();
            default:
                throw new ArgumentException($"Invalid animal type: {type}");
        }
    }
}

In this implementation, we have an interface IAnimal that defines the Speak method, and two classes Dog and Cat that implement the IAnimal interface.

We also have a AnimalFactory class that has a CreateAnimal method which takes a string type as input and returns an instance of an IAnimal implementation based on the type.

To use the factory, you can simply call the CreateAnimal method on the AnimalFactory class, like this:

AnimalFactory factory = new AnimalFactory();
IAnimal dog = factory.CreateAnimal("dog");
IAnimal cat = factory.CreateAnimal("cat");

dog.Speak(); // Output: Woof!
cat.Speak(); // Output: Meow!


In this example, we create an instance of the AnimalFactory class, and use it to create instances of the Dog and Cat classes by calling the CreateAnimal method with the appropriate type. The Speak method of each animal is then called to output the appropriate sound.

This example demonstrates how the Factory pattern can be used to create objects in a flexible and extensible way, without knowing the exact implementation details of each object.

0 comments:

Post a Comment

Please do not enter any spam link in the message box.