Factory Method Design Pattern C#

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
FactoryMethodExample

namespace TestFactoryMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            CarFactory carFactory = new SwiftCarFactory();
            ICar car = carFactory.GetCar();
            Console.ReadKey();
        }
    }

    /// <summary>
    /// Product
    /// </summary>
    public interface ICar
    {
        void BuildCar();
    }

    /// <summary>
    /// Concrete Product1
    /// </summary>
    public class SwiftCar : ICar
    {
        public SwiftCar()
        {
            Console.WriteLine("Swift car: Initialized...");
        }

        public void BuildCar()
        {
            Console.WriteLine("Swift car: Building...");
        }

        public void RunSwiftCarQualityCheck()
        {
            Console.WriteLine("Swift car: Quality Check is Successful...");
        }
    }

    /// <summary>
    /// Concrete Product2
    /// </summary>
    public class AltoCar : ICar
    {
        public AltoCar()
        {
            Console.WriteLine("Alto car: Initializing...");
        }

        public void BuildCar()
        {
            Console.WriteLine("Alto car: Building...");
        }

        public void RunAltoCarQualityCheck()
        {
            Console.WriteLine("Alto car: Quality Check is Successful...");
        }
    }

    /// <summary>
    /// Creator
    /// </summary>
    public abstract class CarFactory
    {
        public ICar GetCar()
        {
            ICar car = this.CreateCar();
            return car;
        }

        public abstract ICar CreateCar();
    }

    /// <summary>
    /// Concrete Creator1
    /// </summary>
    public class SwiftCarFactory : CarFactory
    {
        public override ICar CreateCar()
        {
            SwiftCar car = new SwiftCar();
            car.BuildCar();
            car.RunSwiftCarQualityCheck();
            return car;
        }
    }

    /// <summary>
    /// Concrete Creator2
    /// </summary>
    public class AltoCarFactory : CarFactory
    {
        public override ICar CreateCar()
        {
            AltoCar car = new AltoCar();
            car.BuildCar();
            car.RunAltoCarQualityCheck();
            return car;
        }
    }
}

Output:
FactoryMethodOutput

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