mardi 3 juillet 2018

real world example of Abstract Factory Design Pattern in C#

I am writing this question after reading many posts on Abstract Factory Design Pattern in C#.I really cannot make a real world use case sense out of the examples that all those posts provide. All I could see was some basic example of cars/computers/phones etc.I understand that they are important to provide a simple explanation. But I am really unable to map it to anything real world, because if I would really follow such examples, my code would be changing every other week when I would want to bring new objects.

The below is the sample code for it

namespace ClassLibrary1
{

    public interface AbstractProductA { }
    public class ProductA1 : AbstractProductA { }
    public class ProductA2 : AbstractProductA { }


    public interface AbstractProductB { }
    public class ProductB1 : AbstractProductB { }
    public class ProductB2 : AbstractProductB { }


    public interface AbstractFactory
    {
        AbstractProductA CreateProductA();
        AbstractProductB CreateProductB();
    }


    public class ConcreteFactoryA : AbstractFactory
    {
        public AbstractProductA CreateProductA()
        {
            return new ProductA1();
        }

        public AbstractProductB CreateProductB()
        {
            return new ProductB1();
        }
    }

    public class ConcreteFactoryB : AbstractFactory
    {
        public AbstractProductA CreateProductA()
        {
            return new ProductA2();
        }

        public AbstractProductB CreateProductB()
        {
            return new ProductB2();
        }
    }

    public class Client
    {
        private AbstractProductA _productA;
        private AbstractProductB _productB;

        public Client(AbstractFactory factory)
        {
            _productA = factory.CreateProductA();
            _productB = factory.CreateProductB();
        }
    }

}

Now, how to make sense out of it. I can understand how it is working, but it looks so naive. One thing is that maybe the kind of example everybody on tutorial sites are choosing is not the right one.

Also, what benefit is it really giving me. I can do it in the usual non abstract factory kind of way using interfaces and the entire thing would still work just fine (design wise).

Detailed explanation with example is what I am looking for

Aucun commentaire:

Enregistrer un commentaire