Design patterns – Factory

Factory pattern is used to have a single class which decides which object should be created. Of course it’s creational pattern.
For example you could have Circle, Rectangle and Square classes (all of them implement IShape interface) and factory class instantiates appropriate shape based on given parameter.

The interface:

    /// <summary>
    /// Interface for all shapes.
    /// </summary>
    interface IShape
    {
        double Area();
    }

The sample implementation:

    class Circle : IShape
    {
        private readonly double _radius;

        public Circle(double radius)
        {
            _radius = radius;
        }

        public double Area()
        {
            return Math.PI * Math.Pow(_radius, 2);
        }
    }
    class Rectangle : IShape
    {
        private readonly double _sideA;
        private readonly double _sideB;

        public Rectangle(double sideA, double sideB)
        {
            _sideA = sideA;
            _sideB = sideB;
        }

        public double Area()
        {
            return _sideA * _sideB;
        }
    }

The only one parameter passes do factory:

    enum ShapeType
    {
        Square,
        Rectangle,
        Circle,
    }

And finally the factory which produces shapes:

    class RandomShapesFactory
    {
        Random r;

        public RandomShapesFactory()
        {
            r = new Random();
        }

        public IShape Create(ShapeType type)
        {
            switch (type)
            {
                case ShapeType.Circle:
                    return new Circle(r.Next());
                case ShapeType.Rectangle:
                    return new Rectangle(r.Next(), r.Next());
                case ShapeType.Square:
                    return new Square(r.Next());
                default:
                    throw new NotImplementedException();
            }

        }
    }

Now we can call factory, pass the parameter and it will create appropriate object:

        private static void FactoryUsage()
        {
            var factory = new RandomShapesFactory();
            var shapes = new List<IShape>();
            shapes.Add(factory.Create(ShapeType.Square));
            shapes.Add(factory.Create(ShapeType.Rectangle));
            shapes.Add(factory.Create(ShapeType.Circle));

            foreach(var shape in shapes)
            {
                Console.WriteLine($"Shape area is {shape.Area()}");
            }

        }
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