C# Design Pattern–Factory Method

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Factory
{
    class Program
    {
        // Main Entry for execution
        static void Main(string[] args)
        {
            // Create an array of Factory Instances
            Factory[] _factory = new Factory[3];
            _factory[0] = new TwoWheeler();
            _factory[1] = new FourWheeler();
            _factory[2] = new CompactFourWheeler();

            // Iterate Factory Instances and get relavant data
            Vehicle _vehicle;
            foreach (Factory f in _factory)
            {
                _vehicle = f.GetVehicle();
                Console.WriteLine(_vehicle.GetVehicleId());
            }

            // Hold the console without disappearing
            Console.ReadLine();
        }
    }

    #region Vehicles

    // Base type of Vehicle
    abstract class Vehicle
    {
        public abstract string GetVehicleId();
    }

    // Extend Vehicle to get a Car
    class Car : Vehicle
    {
        public override string GetVehicleId()
        {
            return "Car";
        }
    }

    // Extent Vehicle to get a Bike
    class Bike : Vehicle
    {
        public override string GetVehicleId()
        {
            return "Bike";
        }
    }

    // Extent Bus to get a Bus
    class Bus : Vehicle
    {
        public override string GetVehicleId()
        {
            return "Bus";
        }
    }

    #endregion


    #region Factory Classes

    // Abstract Factory Class
    abstract class Factory
    {
        public abstract Vehicle GetVehicle();
    }

    // Extend Factory Class with for a Two Wheeler
    class TwoWheeler : Factory
    {
        public override Vehicle GetVehicle()
        {
            return new Bike();
        }
    }

    // Extend Factory Class with for a Four Wheeler 
    class FourWheeler : Factory
    {
        public override Vehicle GetVehicle()
        {
            return new Bus();
        }
    }

    // Extend Factory Class with for a Compact Four Wheeler
    class CompactFourWheeler : Factory
    {
        public override Vehicle GetVehicle()
        {
            return new Car();
        }
    }

    #endregion
}
Output - 
Factory1

You may also like...

One Pingback/Trackback