Search This Blog

Thursday, October 24, 2013

Factory Design Pattern C#

C# > Design Patterns > Factory

The factory completely abstracts the creation and initialization of the product from the client.

This indirection enables the client to focus on its role in the application without concerning itself with the details of how the product is created.

In this way the product implementation changes over time and the client remains unchanged.

Model:

Client -> (uses) -> Factory -> (creates) - > Product

 

Example:

Database factory class

                public enum DbOptions
        {
            SQLServer,
            Oracle
        }

        public interface IDatabase
        {
            string Connect();
        }

        public class clsSQlServer : IDatabase
        {
            public string Connect()
            {
                return ("You connected to SQlServer");
            }
        }
        public class clsOracle : IDatabase
        {
            public string Connect()
            {
                return ("You connected to Oracle");
            }
        }
        public class clsUnknown : IDatabase
        {
            public string Connect()
            {
                return ("Unknown database");
            }
        }

        public class DatabaseChoice // Factory class
        {
            static public IDatabase getDBObj(DbOptions db)

            {
                IDatabase objDb = null;
                if (db == DbOptions.SQLServer)
                {
                    objDb = new clsSQlServer();
                }
                else if (db == DbOptions.Oracle)
                {
                    objDb = new clsOracle();
                }

                // In the future if will use MySql only add here
                //else if (db == DbOptions.MySql)
                //{
                //    objDb = new clsMySql();
                //}
                else
                {
                    objDb = new clsUnknown();
                }
                return objDb;
            }
         }
// client

IDatabase objDb = DatabaseChoice.getDBObj(DbOptions.Oracle);
MessageBox.Show(objDb.Connect());