sabato 27 aprile 2019

Design Patterns : Factory Pattern


Factory pattern is a pattern to create objects from a factory, when 2 objects are similar, to avoid casting.
You have to create an abstract base class with some methods and one or more concrete classes that inherit the base class, then you have to create a factory class that has a method that return a base class, the class returned is based on the parameters of the method.

abstract class Vehicle
{
       public abstract Run();
}

class Car : Vehichle
{
      public override Run()
      {
          // implement run for a car
      }
}

class Motorcycle : Vehichle
{
      public override Run()
      {
          // implement run for a motorcycle
      }
}

class NullMobile : Vehichle
{
      public override Run()
      {
          // do nothing
      }
}


public static class Factory
{
       public Vehicle GetVehicle(string type)
      {
            if (type.Equals("car"))
                   return new Car();
            else if (type.Equals("motorcycle"))
                   return new Motorcycle();
            else
                   return new NullMobile();
      }
}

Usage:
var newCar = Factory.GetVehicle("car);
 newCar.Run();

Nessun commento:

Posta un commento