Design Patterns – Factory

By | 23/09/2019

From https://en.wikipedia.org/wiki/Factory_method_pattern:
“In class-based programming, the factory method pattern is a  creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.”

In this post, we will see how to use this pattern, for creating a simple console application that runs the four mathematical operations on two numbers.
We Open Visual Studio and we create a Console application:

First of all, we create an interface called “IOperation”, which contains a method called RunOperation that we will implement in every single operation class:

public interface IOperation
{
     decimal RunOperation(int val1, int val2);
}



Now, we create one class for every single mathematical operation, inheriting the interface IOperation:

public class Addition : IOperation
{
     public decimal RunOperation(int val1, int val2)
     {
          return val1 + val2;
     }
}



public class Subtraction : IOperation
{
     public decimal RunOperation(int val1, int val2)
     {
          return val1 - val2;
     }
}



public class Multiplication : IOperation
{
     public decimal RunOperation(int val1, int val2)
     {
          return val1 * val2;
     }
}



public class Division : IOperation
{
     public decimal RunOperation(int val1, int val2)
     {
          return val1/val2;
     }
}



Then, we create a static class called Operation that we will use to instantiate the correct operation Class, based on the operation type in input:

public static class Operations
{
      public static IOperation SelectOperation(string OperationSelected)
      {
           switch (OperationSelected)
           {
               case "+":
                   return new Addition();
               case "-":
                   return new Subtraction();
              case "*":
                   return new Multiplication();
               case "/":
                   return new Division();
               default:
                   throw new ArgumentException("Attention! This operation doesn't exist.");
           }
      }
}



Finally, we create the Program file:

class Program
{
    static void Main(string[] args)
    {
         Console.WriteLine("Start program");
         Console.WriteLine("Insert 'Q' as operation, in order to quit the program");

         while (true)
         {
              Console.WriteLine("Insert the first value");
              // In a real program, we must verify the input
              int inputval1 = System.Convert.ToInt32(Console.ReadLine());

              Console.WriteLine("Insert the second value");
              // In a real program, we must verify the input
              int inputval2 = System.Convert.ToInt32(Console.ReadLine());

              Console.WriteLine("Insert the operation");
              // In a real program, we must verify the input
              string inputOperation = Console.ReadLine().Trim();

              if (inputOperation == "Q")
                  Environment.Exit(0);

              try
              {
                  // Here, we will instantiate the correct class, based on the value of inputOperation
                  var SelectedOperation = Operations.SelectOperation(inputOperation);

                  Console.WriteLine($"The result is: {SelectedOperation.RunOperation(inputval1, inputval2)}");
                  Console.WriteLine();
                  Console.WriteLine("-----------------------------------");
              }
              catch(Exception ex)
              {
                  Console.WriteLine(ex.Message);
              }
         }
    }
}



If we run the program, this will be the result:

CORRECT INPUT

WRONG INPUT

EXIT FROM THE APPLICATION



Leave a Reply

Your email address will not be published. Required fields are marked *