Design patterns

Posted on Actualizado enn

Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects.

The 23 Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral (for a complete list see below).

  • CREATIONAL PATTERNS
    • Abstract factory *
    • Builder
    • Factory Method *
    • Prototype
    • Singleton
  • STRUCTURAL PATTERNS
    • Adapter *
    • Bridge
    • Composite *
    • Decorator *
    • Facade
    • Flyweight
    • proxy
  • BEHAVIORAL PATTERS
    • Chain of responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer *
    • State
    • Strategy *
    • Template Method *
    • Visitor

*Commons and easiers patters

Singleton (just one instance):

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

Strategy

UML class diagram

using System;
 
namespace DoFactory.GangOfFour.Strategy.Structural
{
  /// 
  /// MainApp startup class for Structural
  /// Strategy Design Pattern.
  ///
  class MainApp
  {
    /// 
    /// Entry point into console application.
    ///
    static void Main()
    {
      Context context;
 
      // Three contexts following different strategies
      context = new Context(new ConcreteStrategyA());
      context.ContextInterface();
 
      context = new Context(new ConcreteStrategyB());
      context.ContextInterface();
 
      context = new Context(new ConcreteStrategyC());
      context.ContextInterface();
 
      // Wait for user
      Console.ReadKey();
    }
  }
 
  /// 
  /// The 'Strategy' abstract class
  ///
  abstract class Strategy
  {
    public abstract void AlgorithmInterface();
  }
 
  /// 
  /// A 'ConcreteStrategy' class
  ///
  class ConcreteStrategyA : Strategy
  {
    public override void AlgorithmInterface()
    {
      Console.WriteLine(
        "Called ConcreteStrategyA.AlgorithmInterface()");
    }
  }
 
  /// 
  /// A 'ConcreteStrategy' class
  ///
  class ConcreteStrategyB : Strategy
  {
    public override void AlgorithmInterface()
    {
      Console.WriteLine(
        "Called ConcreteStrategyB.AlgorithmInterface()");
    }
  }
 
  /// 
  /// A 'ConcreteStrategy' class
  ///
  class ConcreteStrategyC : Strategy
  {
    public override void AlgorithmInterface()
    {
      Console.WriteLine(
        "Called ConcreteStrategyC.AlgorithmInterface()");
    }
  }
 
  /// 
  /// The 'Context' class
  ///
  class Context
  {
    private Strategy _strategy;
 
    // Constructor
    public Context(Strategy strategy)
    {
      this._strategy = strategy;
    }
 
    public void ContextInterface()
    {
      _strategy.AlgorithmInterface();
    }
  }
}

Output

Called ConcreteStrategyA.AlgorithmInterface()
Called ConcreteStrategyB.AlgorithmInterface()
Called ConcreteStrategyC.AlgorithmInterface()
Real World

using System;
using System.Collections.Generic;

namespace DoFactory.GangOfFour.Strategy.RealWorld
{
  ///
  /// MainApp startup class for Real-World
  /// Strategy Design Pattern.
  ///

  class MainApp
  {
    ///
    /// Entry point into console application.
    ///

    static void Main()
    {
      // Two contexts following different strategies
      SortedList studentRecords = new SortedList();

      studentRecords.Add("Samual");
      studentRecords.Add("Jimmy");
      studentRecords.Add("Sandra");
      studentRecords.Add("Vivek");
      studentRecords.Add("Anna");

      studentRecords.SetSortStrategy(new QuickSort());
      studentRecords.Sort();

      studentRecords.SetSortStrategy(new ShellSort());
      studentRecords.Sort();

      studentRecords.SetSortStrategy(new MergeSort());
      studentRecords.Sort();

      // Wait for user
      Console.ReadKey();
    }
  }

  ///
  /// The 'Strategy' abstract class
  ///

  abstract class SortStrategy
  {
    public abstract void Sort(List<string> list);
  }

  ///
  /// A 'ConcreteStrategy' class
  ///

  class QuickSort : SortStrategy
  {
    public override void Sort(List<string> list)
    {
      list.Sort(); // Default is Quicksort
      Console.WriteLine("QuickSorted list ");
    }
  }

  ///
  /// A 'ConcreteStrategy' class
  ///

  class ShellSort : SortStrategy
  {
    public override void Sort(List<string> list)
    {
      //list.ShellSort(); not-implemented
      Console.WriteLine("ShellSorted list ");
    }
  }

  ///
  /// A 'ConcreteStrategy' class
  ///

  class MergeSort : SortStrategy
  {
    public override void Sort(List<string> list)
    {
      //list.MergeSort(); not-implemented
      Console.WriteLine("MergeSorted list ");
    }
  }

  ///
  /// The 'Context' class
  ///

  class SortedList
  {
    private List<string> _list = new List<string>();
    private SortStrategy _sortstrategy;

    public void SetSortStrategy(SortStrategy sortstrategy)
    {
      this._sortstrategy = sortstrategy;
    }

    public void Add(string name)
    {
      _list.Add(name);
    }

    public void Sort()
    {
      _sortstrategy.Sort(_list);

      // Iterate over list and display results
      foreach (string name in _list)
      {
        Console.WriteLine(" " + name);
      }
      Console.WriteLine();
    }
  }
}
Output
QuickSorted list
Anna
Jimmy
Samual
Sandra
VivekShellSorted list
Anna
Jimmy
Samual
Sandra
VivekMergeSorted list
Anna
Jimmy
Samual
Sandra
Vivek
Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s