Add

Abstract Factory Pattern

Abstract Factory pattern is used when you want to create families of products. It relies on composition so methods exposed in factory interface are responsible for the creation of objects.


Abstract Factory Pattern Example


Here is an example of a Abstract Factory pattern with 2 families of products.



Abstract Factory Pattern CD


    // Abstract Factory
    abstract class MobileFactory
    {

        public abstract SimpleMobile CreateSimpleMobile();

        public abstract AdvancedMobile CreateAdvancedMobile();

    }

    //ConcreteFactoryOne
    class SamsungMobileFactory : MobileFactory
    {

        // CreateProductX
        public override SimpleMobile CreateSimpleMobile()
        {

            return new SamsungSimpleMobile();

        }

        // CreateProductY
        public override AdvancedMobile CreateAdvancedMobile()
        {

            return new SamsungAdvancedMobile();

        }

    }

    //ConcreteFactoryTwo
    class HTCMobileFactory : MobileFactory
    {
        // CreateProductX
        public override SimpleMobile CreateSimpleMobile()
        {

            return new HTCSimpleMobile();

        }

        // CreateProductY
        public override AdvancedMobile CreateAdvancedMobile()
        {

            return new HTCAdvancedMobile();

        }

    }

    // AbstractProductX
    abstract class SimpleMobile
    {

    }

    // AbstractProductY
    abstract class AdvancedMobile
    {


    }

    // ProductXOne
    class SamsungSimpleMobile : SimpleMobile
    {

    }

    // ProductYOne
    class SamsungAdvancedMobile : AdvancedMobile
    {

    }

    // ProductXTwo
    class HTCSimpleMobile : SimpleMobile
    {

    }

    // ProductYTwo
    class HTCAdvancedMobile : AdvancedMobile
    {
    }

    class Client
    {

        private SimpleMobile _abstractProductX;

        private AdvancedMobile _abstractProductY;

        public Client(MobileFactory factory)
        {

            _abstractProductX = factory.CreateSimpleMobile();
            _abstractProductY = factory.CreateAdvancedMobile();

        }

        public void Print()
        {
            Console.WriteLine(this._abstractProductX.ToString() + " Created!");
            Console.WriteLine(this._abstractProductY.ToString() + " Created!");
        }



    }

    class Program
    {
        static void Main(string[] args)
        {

            MobileFactory abstractFactoryOne = new SamsungMobileFactory();

            Client client1 = new Client(abstractFactoryOne);

            client1.Print();


            MobileFactory abstractFactoryTwo = new HTCMobileFactory();

            Client client2 = new Client(abstractFactoryTwo);

            client2.Print();



            Console.ReadKey();

        }

    }


Abstract Factory Pattern Output


Abstract Factory Pattern Output