Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Thursday, July 28, 2016

Implementing the Repository Pattern in C# with Entity Framework

If you are looking to implement the Repository Pattern in C#, you may find lots and lots and LOTS of conflicting solutions about how to implement the Repository Pattern in your own application.

If you just do a quick search just on MSDN, you will find articles such as the following:

https://blogs.msdn.microsoft.com/wriju/2013/08/23/using-repository-pattern-in-entity-framework/

http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

If you look through the examples above, you will see that they offer different solutions to the same Repository Pattern problem.  However, the second example provides the ability to create a Generic Repository which is much more appealing than creating a different repository for each class in your entire data model!

Unfortunately, the MSDN example lacks a definition of a generic interface which GenericRepository implements.  Looking at the code, you can derive your own IRepository interface, but the example still lacks support for a Dependency Injection or IoC container.  As you will readily notice, the example directly requires an implementation of SchoolContext to be created.  The way in which the example gets around direct creation of the SchoolContext is by using a Unit of Work class which handles the creation of this instance.  While the Unit of Work class can be useful in aggregating multiple repositories, it may not make much sense for instances when you simply need a single repository, which is why an IoC container is very useful!

So how exactly do you get Ninject to work in this scenario?

For Ninject, you simply use the following code to inject your SchoolContext instance:


You can simply add the following code to your RegisterServices method inside of your NinjectWebCommon.cs file and this should do the trick for you!

Thursday, June 26, 2014

Head First Design Patterns Code Download

If you are looking for code downloads for the Head First Design Patterns book, you can find them here: http://www.headfirstlabs.com/books/hfdp/

In addition to downloading the Java code samples, you can even download code samples in C#!
http://www.msquaredweb.com/DesignPatterns/HeadFirstDesignPatternsInCSharp.zip

Wednesday, June 25, 2014

The Observer/Publish-Subscribe Pattern in C#

The Observer Pattern is most commonly known also as the Publish/Subscribe Pattern.

The definition of the Observer Pattern is as follows:

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically (Head First Design Patterns-the observer pattern).

Below is the corresponding code in C# for the Observer pattern found in the Head First Design Patterns book:
 
void Main()
{
    WeatherData weatherData = new WeatherData();
 
            CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
 
            weatherData.setMeasurements(80F, 65F, 30.4F);
            weatherData.setMeasurements(82F, 70F, 29.2F);
            weatherData.setMeasurements(78F, 90F, 29.2F);
}
 
 public class CurrentConditionsDisplay: Observer, DisplayElement
    {
        private float temperature;
        private float humidity;
        private Subject weatherData;
 
        public CurrentConditionsDisplay(Subject weatherData)
        {
            this.weatherData = weatherData;
            weatherData.registerObserver(this);
        }
 
        public void update(float temperature, float humidity, float pressure)
        {
            this.temperature = temperature;
            this.humidity = humidity;
            display();
        }
 
        public void display()
        {
            Console.WriteLine("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity");
        }
    }
    
public interface Observer
    {
        void update(float temp, float humidity, float pressure);
    }
 
    public interface DisplayElement
    {
        void display();
    }
 
public interface Subject
    {
        void registerObserver(Observer o);
        void removeObserver(Observer o);
 
        void notifyObservers();
    }
 
public class WeatherData: Subject
    {
        private ArrayList observers;
        private float temperature;
        private float humidity;
        private float pressure;
 
        public WeatherData()
        {
            observers = new ArrayList();
        }
 
 
        public void registerObserver(Observer o)
        {
            observers.Add(o);
        }
 
        public void removeObserver(Observer o)
        {
            int i = observers.IndexOf(o);
            if (i >= 0)
            {
                observers.RemoveAt(i);
            }//if
        }
 
        public void notifyObservers()
        {
            for (int i = 0; i < observers.Count; i++)
            {
                Observer observer = (Observer)observers[i];
                observer.update(temperature, humidity, pressure);
            }
        }
 
        public void setMeasurements(float temperature, float humidity, float pressure)
        {
            this.temperature = temperature;
            this.humidity = humidity;
            this.pressure = pressure;
            measurementsChanged();
        }
 
        private void measurementsChanged()
        {
            notifyObservers();
        }
    }


If you are looking to use .NET's built-in IObservable interface, you can read more about that here: http://msdn.microsoft.com/en-us/library/dd990377%28v=vs.110%29.aspx

For an example of the Observer Design Pattern based on implementing the IObservable interface, you can find that here: http://msdn.microsoft.com/en-us/library/ee850490%28v=vs.110%29.aspx

Leftover Patterns in Head First Design Patterns

If you have picked up the book "Head First Design Patterns", one of the unfortunate parts of this book is that there are no code samples associated with "leftover patterns".  Instead, the patterns are simply described very briefly.

The Leftover Patterns are:

  1. Bridge Pattern
  2. Builder Pattern
  3. Chain of Responsibility Pattern
  4. Flyweight Pattern
  5. Interpreter Pattern
  6. Mediator Pattern
  7. Memento Pattern
  8. Prototype Pattern
  9. Visitor Pattern

However, C# 3.0 Design Patterns (http://shop.oreilly.com/product/9780596527730.do) DOES cover these Leftover Patterns!!

You can read up more about these patterns here as well as download associated Example Code: http://patterns.cs.up.ac.za/


The Strategy Pattern in C#

The Strategy Pattern is one of the most basic Design Patterns and is largely based on the OOP Principle of favoring Composition over Inheritance.

The Strategy Pattern is officially defined as:

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.  Strategy lets the algorithm vary independently from clients that use it. (Head First Design Patterns-Intro to Design Patterns)

Below is an implementation of the Strategy Pattern in C#:
 
void Main()
{
    Duck mallard = new MallardDuck();
            mallard.performQuack();
            mallard.performFly();
 
            Duck model = new ModelDuck();
            model.performFly();
            model.SetFlyBehavior = new FlyRocketPowered();
            model.performFly();
 
            
}
 
public abstract class Duck
    {
        protected FlyBehavior flyBehavior;
        protected QuackBehavior quackBehavior;
 
        public Duck()
        {
 
        }
 
        public FlyBehavior SetFlyBehavior
        {
            get
            {
                return flyBehavior;
            }
            set
            {
                flyBehavior = value;
            }
 
        }
 
        public QuackBehavior SetQuackBehavior
        {
            get
            {
                return quackBehavior;
            }
            set
            {
                quackBehavior = value;
            }
        }
 
        public abstract void display();
 
        public void performFly()
        {
            flyBehavior.fly();
        }
 
        public void performQuack()
        {
            quackBehavior.quack();
        }
 
        public void swim()
        {
            Console.WriteLine("All ducks float, even decoys!");
        }
 
    }
 
    public class MallardDuck : Duck
    {
        public MallardDuck()
        {
            quackBehavior = new Quack();
            flyBehavior = new FlyWithWings();
 
        }
        public override void display()
        {
            Console.WriteLine("I'm a real Mallard duck");
        }
    }
 
    public class ModelDuck : Duck
    {
        public ModelDuck()
        {
            flyBehavior = new FlyNoWay();
            quackBehavior = new Quack();
        }
        public override void display()
        {
            Console.WriteLine("I'm a model duck");
        }
    }
    
     public interface FlyBehavior
    {
        void fly();
    }
 
 public class FlyWithWings: FlyBehavior
    {
        public void fly()
        {
            Console.WriteLine("I'm flying!");
        }
    }
 
    public class FlyNoWay : FlyBehavior
    {
        public void fly()
        {
            Console.WriteLine("I can't fly");
        }
    }
 
    public class FlyRocketPowered : FlyBehavior
    {
        public void fly()
        {
            Console.WriteLine("I'm flying with a rocket!");
        }
    }
    
    public class Quack: QuackBehavior
    {
        public void quack()
        {
            Console.WriteLine("Quack");
        }
    }
 
    public class MuteQuack : QuackBehavior
    {
        public void quack()
        {
            Console.WriteLine("<<Silence>>");
        }
    }
 
    public class Squeak : QuackBehavior
    {
        public void quack()
        {
            Console.WriteLine("Squeak");
        }
    }
    
    public interface QuackBehavior
    {
        void quack();
    }



Monday, June 23, 2014

The Adapter Pattern in C#

If you need to ever get a class to conform to another interface to provide uniform or predictable functionality, chances are that you will need to use the Adapter Design Pattern.

You can basically think of "real world" adapters such as the AC/DC Power Adapters that you will find with a wide variety of electronic devices or the adapters that you need for power outlets when you travel internationally.

The formal definition of the Adapter Pattern is the following:

The Adapter Pattern converts the interface of a class into another interface the clients expect.  Adapter lets classes work together that couldn't otherwise because of incompatible interfaces (Head First Design Patterns-the adapter pattern)

Since the Head First Design Patterns deals with sample code in Java, I have provided a C# implementation for you instead:

void Main()
{
    MallardDuck duck = new MallardDuck();
 
            WildTurkey turkey = new WildTurkey();
            Duck turkeyAdapter = new TurkeyAdapter(turkey);
 
            Console.WriteLine("The Turkey says....");
            turkey.gobble();
            turkey.fly();
 
            Console.WriteLine("\nThe Duck says....");
            testDuck(duck);
 
            Console.WriteLine("\nThe TurkeyAdapter says...");
            testDuck(turkeyAdapter);
 
}
 
static void testDuck(Duck duck)
        {
            duck.quack();
            duck.fly();
        }
        
public interface Duck
    {
        void quack();
        void fly();
    }
    
  public class MallardDuck : Duck
    {
        public void quack()
        {
            Console.WriteLine("Quack");
        }
 
        public void fly()
        {
            Console.WriteLine("I'm flying");
        }
    }
    
    public interface Turkey
    {
        void gobble();
        void fly();
    }
    
     public class WildTurkey : Turkey
    {
        public void gobble()
        {
            Console.WriteLine("Gobble gobble");
        }
 
        public void fly()
        {
            Console.WriteLine("I'm flying a short distance");
        }
    }
    
     public class TurkeyAdapter: Duck
    {
        private Turkey turkey;
 
        public TurkeyAdapter(Turkey turkey)
        {
            this.turkey = turkey;
        }
        public void quack()
        {
            turkey.gobble();
        }
 
        public void fly()
        {
            for (int i = 0; i < 5; i++)
            {
                turkey.fly();
            }//for
        }
    }

Sunday, June 22, 2014

The Abstract Factory Pattern in C#


The Abstract Factory Pattern builds upon the Factory Method pattern and adds Object Composition to the mix.
The Abstract Factory Pattern is officially defined as the following:
The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. (Head First Design Patterns-the factory pattern)

In “Head First Design Patterns”, the Abstract Factory pattern extends upon the use of the Factory Method by adding control of the various ingredients needed by each of the Pizza Stores.  Therefore, a NY Pizza Store will receive a different set of ingredients vs a Chicago Pizza Store even though the ingredient types are common (sauce, cheese, veggies etc.).
 
Below is the basic pattern code in C# for your review (ingredient classes are left out since they are simple shell classes):
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractFactoryPattern;
 
namespace AbstractFactoryPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            PizzaStore nyStore = new NYPizzaStore();
            Pizza pizza = nyStore.orderPizza("cheese");
            Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");
            Console.ReadKey();
        }
    }
}
 
 
public interface PizzaIngredientFactory
{
  Dough createDough();
  Sauce createSauce();
  Cheese createCheese();
  List<Veggies> createVeggies();
  Pepperoni createPepperoni();
  Clams createClam();
 }//interface
 
public class NYPizzaIngredientFactory: PizzaIngredientFactory
{
  public Dough createDough()
    {
      return new ThinCrustDough();
     }
   public Sauce createSauce()
    {
      return new MarinaraSauce();
     }
    public Cheese createCheese()
    {
       return new ReggianoCheese();
    }
    public List<Veggies> createVeggies()
    {
      List<Veggies> veggies = new List<Veggies> {new Garlic(), new Onion(), new Mushroom(), new RedPepper()};
      return veggies;
    }
    public Pepperoni createPepperoni()
    {
      return new SlicedPepperoni();
     }
     
     public Clams createClam()
     {
       return new FreshClams();
     }
}//class NYPizzaIngredientFactory
 
public class CheesePizza: Pizza
{
  PizzaIngredientFactory ingredientFactory;
  
  public CheesePizza(PizzaIngredientFactory ingredientFactory)
    {
      this.ingredientFactory = ingredientFactory;
    }
    
    public override void prepare()
    {
      Console.WriteLine("Preparing " + this.name);
      dough = ingredientFactory.createDough();
      sauce = ingredientFactory.createSauce();
      cheese = ingredientFactory.createCheese();
     }
}
 
 
// Define other methods and classes here
public abstract class Pizza
{
protected string name;
protected Dough dough;
protected Sauce sauce;
protected List<Veggies> veggies;
protected Cheese cheese;
protected Pepperoni pepperoni;
protected Clams clam;
 
public abstract void prepare();
    
public void bake()
    {
    Console.WriteLine("Bake for 25 minutes at 350");
    }//bake
    
public void cut()
    {
      Console.WriteLine("Cutting the pizza into diagonal slices");
    }//cut
    
public void box()
    {
      Console.WriteLine("Place piza in official PizzaStore box");
    }//box
    
public string Name
    {
    get
        {
        return name;
        }
    set
        {
        name = value;
        }
    }//property: Name
 
    public override string ToString()
    {
        return name;
    }
}
    
public class NYStyleCheesePizza: Pizza
{
    private PizzaIngredientFactory ingredientFactory;
    public NYStyleCheesePizza(PizzaIngredientFactory ingredientFactory)
    {
        this.ingredientFactory = ingredientFactory;
        }
 
    public  override  void prepare()
    {
        Console.WriteLine("Preparing " + name);
        dough = ingredientFactory.createDough();
        sauce = ingredientFactory.createSauce();
        cheese = ingredientFactory.createCheese();
    }
    }//class: NYStyleCheesePizza
    
public abstract class PizzaStore
{
  public Pizza orderPizza(string type)
    {
    Pizza pizza;
    
    pizza = createPizza(type);
    
    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();
    
    return pizza;
    }
    
    protected abstract Pizza createPizza(string type);
}//class: PizzaStore
 
public class NYPizzaStore: PizzaStore
{
    protected override Pizza createPizza(string item)
    {
      Pizza pizza = null;
      PizzaIngredientFactory ingredientFactory = new NYPizzaIngredientFactory();
    if (item.Equals("cheese"))
    {
     pizza = new NYStyleCheesePizza(ingredientFactory);
     pizza.Name = "New York Style Cheese Pizza";
        return pizza;
    }//if
    else
    {
      return null;
    }//else
    }
}//class: NYPizzaStore

 

 

The Factory Method Pattern in C#


If you are not familiar with the Factory Method pattern, it is a well known design pattern officially defined as the following:
The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate.  Factory Method lets a class defer instantiation to subclasses.  (Head First Design Patterns-the factory pattern)
In the example provided in the book “Head First Design Patterns”, essentially a Pizza Store has grown into a franchise that needs to create different styles of pizzas based on different Pizza Stores in the franchise.  So how is that handled?  Essentially, allowing each Pizza Store in the franchise decide how to make the various styles of pizzas they will be creating (through subclasses/inheritance) but providing the overall framework for how the pizzas will be created.
The original source code is provided in Java in this book, therefore, I have provided a C# version for .NET Developers who want to begin using this pattern in their own development:
void Main()

{

    PizzaStore nyStore = new NYPizzaStore();

    Pizza pizza = nyStore.orderPizza("cheese");

    Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");

}

 

 

 

// Define other methods and classes here

public abstract class Pizza

{

protected string name;

protected string dough;

protected string sauce;

protected ArrayList toppings = new ArrayList();

 

public void prepare()

    {

    Console.WriteLine("Preparing " + name);

    Console.WriteLine("Tossing dough....");

    Console.WriteLine("Adding sauce...");

    Console.WriteLine("Adding toppings:");

    for (int i=0; i< toppings.Count; i++)

    {

      Console.WriteLine(" " + toppings[i]);

     }//for

    }//prepare

    

public void bake()

    {

    Console.WriteLine("Bake for 25 minutes at 350");

    }//bake

    

public void cut()

    {

      Console.WriteLine("Cutting the pizza into diagonal slices");

    }//cut

    

public void box()

    {

      Console.WriteLine("Place piza in official PizzaStore box");

    }//box

    

public string Name

    {

    get

        {

        return name;

        }

    }//property: Name

}

    

public class NYStyleCheesePizza: Pizza

    {

    public NYStyleCheesePizza()

        {

          name = "NY Style Sauce and Cheese Pizza";

          dough = "Thin Crust Dough";

          sauce = "Marinara Sauce";

          toppings.Add("Grated Reggiano Cheese");

        }

    }//class: NYStyleCheesePizza

    

public abstract class PizzaStore

{

  public Pizza orderPizza(string type)

    {

    Pizza pizza;

    

    pizza = createPizza(type);

    

    pizza.prepare();

    pizza.bake();

    pizza.cut();

    pizza.box();

    

    return pizza;

    }

    

    protected abstract Pizza createPizza(string type);

}//class: PizzaStore

 

public class NYPizzaStore: PizzaStore

{

    protected override Pizza createPizza(string item)

    {

    if (item.Equals("cheese"))

    {

     return new NYStyleCheesePizza();

    }//if

    else

    {

      return null;

    }//else

    }

}//class: NYPizzaStore

    

Saturday, March 10, 2012

Existing Design Patterns in Microsoft.Net

You may not know it, but if you have been working with the Microsoft.Net platform for any length of time, there are numerous Design Patterns which have been implemented natively by the Microsoft.Net Framework.

Here are just some of the common Design Patterns:


  1. If you have ever worked with creating a Collection and then looping through it using a foreach loop, you have used the Iterator Pattern.
  2. If you have ever used a StringBuilder to build strings (hence its name), you have used the Builder Pattern.
  3. If you have ever used Serialization of objects using XML Serialization attributes or DataContract Serialization attributes for WCF, you have used a form of the Decorator Pattern.
  4. If you have ever used Web Services (ASMX or WCF), you have used the Proxy Pattern.
  5. If you have ever worked with a static class constructor, you have used the Singleton Pattern.
  6. If you have ever worked with the DbFactory class in ADO.Net, you have used the Factory Method Pattern.
  7. If you have ever worked with DataBinding expressions in ASP.Net or just plain old XML, you have used the Interpreter Pattern.
  8. If you have ever written extension methods, you have used the Bridge Pattern.
  9. If you have ever worked with a SqlDataAdapter object, you have used the Adapter Pattern.
  10. If you have ever worked with a SqlCommand object, you have used the Command Pattern.
  11. If you have ever used the Copy or Clone methods on a DataSet, you have used the Prototype Pattern.
  12. If you have ever worked with Events (such as a Button Click event), you have used the Observer Pattern.
  13. If you have ever worked with templated controls in ASP.Net such as the Wizard control or the various ASP.Net AJAX Controls, you have used the Template Method Pattern.
  14. If you have ever worked with a State Machine Workflow in SharePoint, you have used the State Pattern.
  15. If you have ever worked with any of the various Providers such as MembershipProvider, RoleProvider, ProfileProvider or SiteMapProvider, you have used multiple Design Patterns:
    • Strategy Pattern
    • Factory Method Pattern
    • Singleton Pattern
    • Facade Pattern



So if someone ever asks you if you have ever worked with Design Patterns, you HAVE!

Monday, November 21, 2011

Abstract Factory Design Pattern

This is some sample code from C# 3.0 Design Patterns by Judith Bishop outlining the Abstract Factory Design Pattern:

using System;

namespace AbstractFactoryPattern {
  //  Abstract Factory        D-J Miller and Judith Bishop Sept 2007
  //  Uses generics to simplify the creation of factories
  
  interface IFactory<Brand>
    where Brand : IBrand {
    IBag CreateBag();
    IShoes CreateShoes();
  }

  // Conctete Factories (both in the same one)
  class Factory<Brand> : IFactory<Brand>
    where Brand : IBrand, new() {
    public IBag CreateBag() {
      return new Bag<Brand>();
    }

    public IShoes CreateShoes() {
      return new Shoes<Brand>();
    }
  }

  // Product 1
  interface IBag {
    string Material { get; }
  }

  // Product 2
  interface IShoes {
    int Price { get; }
  }

  // Concrete Product 1
  class Bag<Brand> : IBag
    where Brand : IBrand, new() {
    private Brand myBrand;
    public Bag() {
      myBrand = new Brand();
    }

    public string Material { get { return myBrand.Material; } }
  }

  // Concrete Product 2
  class Shoes<Brand> : IShoes
    where Brand : IBrand, new() {
      
    private Brand myBrand;
      
    public Shoes() {
      myBrand = new Brand();
    }

    public int Price { get { return myBrand.Price; } }
  }

  interface IBrand {
    int Price { get; }
    string Material { get; }
  }

  class Gucci : IBrand {
    public int Price { get { return 1000; } }
    public string Material { get { return "Crocodile skin"; } }
  }

  class Poochy : IBrand {
    public int Price { get { return new Gucci().Price / 3; } }
    public string Material { get { return "Plastic"; } }
  }

  class Groundcover : IBrand {
    public int Price { get { return 2000; } }
    public string Material { get { return "South african leather"; } }
  }

  class Client<Brand>
    where Brand : IBrand, new() {
    public void ClientMain() { //IFactory<Brand> factory)
      IFactory<Brand> factory = new Factory<Brand>();

      IBag bag = factory.CreateBag();
      IShoes shoes = factory.CreateShoes();

      Console.WriteLine("I bought a Bag which is made from " + bag.Material);
      Console.WriteLine("I bought some shoes which cost " + shoes.Price);
    }
  }

  static class Program {
    static void Main() {
      // Call Client twice
      new Client<Poochy>().ClientMain();
      new Client<Gucci>().ClientMain();
      new Client<Groundcover>().ClientMain();
    }
  }
} 
 
Based on the above code, we can readily notice that this does not differ significantly from the 
Factory Method Design Pattern in that it is still heavily reliant on Interfaces.  In this case,
however, the usage of C# Generics has further simplified the process of specifying
concrete class implementations, thus allowing a Class Name to be specified as a 
parameter rather than an actual concrete class instance.
The Abstract Factory Design pattern primarily differs from the Factory Method class in that
the individual classes or "factories" are responsible for handling the business
logic for processing, whereas in the Factory Method Design Pattern, this is wholly contained
within the logic of a single method.  In addition, the Abstract Factory Design Pattern
is leverage to create a group of related products (in this case, bags and shoes) whereas
the Factory Method also concerned itself with the instantiation of only a single
class based on a common Interface.  Therefore, the abstraction in this case is to the 
level of encapsulating the internal details and logic of creating a "factory" 
rather than creating a specific single class instance.

Factory Method Design Pattern

This is some sample code from C# 3.0 Design Patterns by Judith Bishop outlining the Factory Method Design Pattern:

using System;
  using System.Collections;

  class FactoryPattern {
  
  // Factory Method Pattern       Judith Bishop 2006
  //  Example of exporting from different suppliers
    
  interface IProduct {
    string ShipFrom();
  }

  class ProductA : IProduct {
    public String ShipFrom () {
      return " from South Africa";
    }
  }
  
  class ProductB : IProduct {
    public String ShipFrom () {
            return "from Spain";
    }
  }

  class DefaultProduct : IProduct {
    public String ShipFrom () {
            return "not available";
    }
  }

  class Creator {
    public  IProduct FactoryMethod(int month) {
      if (month >= 4 && month <=11)
        return new ProductA();
      else 
      if (month == 1 || month == 2 || month == 12)
        return new ProductB();
      else 
        return new DefaultProduct();
    }
  }
  
    static void Main() {
      Creator c = new Creator();
      IProduct product;
        
      for (int i=1; i<=12; i++) {
        product = c.FactoryMethod(i);
        Console.WriteLine("Avocados "+product.ShipFrom());
      }
    }
  }

So by looking at the code, you can probably get a good feel for what the code is trying to accomplish.

There are 3 products which all need to implement common shipping functionality but need to ship from 3 different locations. Therefore, this is a perfect candidate for implementing an Interface across all of the class implementations. By implementing a common Interface, the classes can easily be swapped for one another (called "polymorphism"). Since all of the classes are interchangeable, there only needs to be a set of criteria which dictates which class is actually instantiated and utilized within the Main method.

In this case, the Factory method is responsible for accepting that parameter (in this case, the month) and then returning the appropriate instance of the class based on the internally developed logic which has been conveniently encapsulated into a single method. The Main method can now simply be oblivious to the actual instance of the class that is required. The class is returned as an instance of an Interface and the only parameter that is required to be known is the month. The Factory Method in this manner also assists in the principles of encapsulation and decoupling.