Thursday, October 12, 2017

Factory pattern in C#

Ok, so the idea is to create a class able to mass-produce instances of a different class or classess.
First, let's create something to be produced by our Factory class as in product:

    abstract class Product
    {
        public abstract ProductType GetProductType();
    }

    class Car : Product
    {
        public override ProductType GetProductType()
        {
            return ProductType.Car;
        }
    }

    class Motorcycle : Product
    {
        public override ProductType GetProductType()
        {
            return ProductType.Motorcycle;
        }
    }

    class Airplane : Product
    {
        public override ProductType GetProductType()
        {
            return ProductType.Motorcycle;
        }
    }

You don't have to do it exactly this way, I mean, you can use interfaces if you want or even concrete unrelated classes (which you can return from Factory as Object).

Now we need to make some Factories. I create one for each type of product, but again, this one is up to you, you can implement this functionality as you please:

    abstract class Factory
    {
        public abstract Product createProduct();
    }

    class CarFactory : Factory 
    {
        public override Product createProduct()
        {
            return new Car();
        }
    }

    class MotorcycleFactory : Factory
    {
        public override Product createProduct()
        {
            return new Motorcycle();
        }
    }

    class AirplaneFactory : Factory
    {
        public override Product createProduct()
        {
            return new Airplane();
        }
    }

Well, I guess, that's about it.

No comments:

Post a Comment