Simple Factory Design Pattern C#

Creates objects without exposing the instantiation logic to the client. Refers to the newly created object through a common interface

SimpleFactory

namespace TestSimpleFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            OperatingSystemFactory osFactory = new OperatingSystemFactory();
            IOperatingSystem windows = osFactory.GetOperatingSytemByType(OperatingSystemType.Windows);
            windows.DisplayWelcomeMessage();
            Console.ReadKey();
        }

        public interface IOperatingSystem
        {
            void DisplayWelcomeMessage();
        }

        public class Windows : IOperatingSystem
        {
            public void DisplayWelcomeMessage()
            {
                Console.WriteLine("Welcome to Windows Operating System");
            }
        }

        public class Linux : IOperatingSystem
        {
            public void DisplayWelcomeMessage()
            {
                Console.WriteLine("Welcome to Linux Operating System");
            }
        }       

        /// <summary>
        /// SimpleFactory
        /// </summary>
        public class OperatingSystemFactory
        {
            public IOperatingSystem GetOperatingSytemByType(OperatingSystemType osType)
            {
                if (osType == OperatingSystemType.Windows)
                {
                    return new Windows();
                }
                else if (osType == OperatingSystemType.Linux)
                {
                    return new Linux();
                }                

                return null;
            }
        }

        public enum OperatingSystemType
        {
            Windows,
            Linux
        }
    }
}

Output:
SimpleFactoryOutput

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