Sunday, September 22, 2013

Here are some more along with the previous post:

Decorator Pattern :  Here we don't change the interface like we did in the adapter. We wrap the object to add new functionalities. Extension methods is an example as well as a specific example with Stream class. BufferedStream, FileStream can all be wrapped from existing stream.

Iterator pattern :  This is evident from the IEnumerable pattern in .Net. This is very helpful with LINQ expressions where you can take the collection as Enumerable and invoke the standard query operators. The GetEnumerator() method and the MoveNext() on the IEnumerable enable the iteration.

Observer pattern : This is used to notify changes from one class to the other. Here we use an interface so that any object can subscribe to notifications that are invoked by calling the Notify method on the Observer.
public interface Observer {
void Notify(State s);
}
public class Subject
{
  private List<IObservers> observers;
  public void Add(IObserver);
  public void Remove(IObserver);
  public void NotifyObservers(State s)
  {
     observers.ForEach (x => x.Notify(s));
  }
}

Strategy pattern : When we are able to switch different ways to do the same task such as say sorting where we take a parameter for different comparisions, we implement the strategy pattern. Here the IComparer interface enables different comparisions between elements so that the same sorting operation on the same input can yield different results based on the different algorithms used. This pattern is called the Strategy pattern.
public class ArrayList : IList, ICollection, IEnumerable, ICloneable
{
    public virtual void Sort(IComparer comparer);
}

No comments:

Post a Comment