Friday, November 19, 2010

Command Design Pattern - Behavioural

1.1     Definition

-  Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and  support undoable operations.      
-       In Command pattern objects are used to represent actions. A Command object encapsulates an action and its parameters.
      

1.2     Intent

There are times when developing an application framework that you need to pass requests between objects without knowing anything about operation requested or the receiver of the request. By encapsulating the request as an object itself, one can "parameterize clients with different requests, queue or log requests, and support undoable operations." (GOF) This is the Command behavioral design pattern. You can separate the requesting object from the object that "knows" how to fulfill it.

1.3     Motivation

In object-oriented programming, the Command pattern is a design pattern in which objects are used to represent actions. A command object encapsulates an action and its parameters.
For example, a printing library might include a PrintJob class. A user would typically create a new PrintJob object, set its properties (the document to be printed, the number of copies, and so on), and finally call a method to send the job to the printer.
In this case, the same functionality could be exposed via a single SendJobToPrinter() procedure with many parameters. As it takes more code to write a command class than to write a procedure, there must be some reason to use a class. There are many possible reasons:

·         It can improve API design. In some cases, code that uses a command object is shorter, clearer, and more declarative than code that uses a procedure with many parameters. This is particularly true if a caller typically uses only a handful of the parameters and is willing to accept sensible defaults for the rest.
·         A command object is convenient temporary storage for procedure parameters. It can be used while assembling the parameters for a function call and allows the command to be set aside for later use.
·         A class is a convenient place to collect code and data related to a command. A command object can hold information about the command, such as its name or which user launched it; and answer questions about it, such as how long it will likely take.
·         Treating commands as objects enables data structures containing multiple commands. A complex process could be treated as a tree or graph of command objects. A thread pool could maintain a priority queue of command objects consumed by worker threads.
·         Treating commands as objects supports undo-able operations, provided that the command objects are stored (for example in a stack)
·         The command is a useful abstraction for building generic components, such as a thread pool, that can handle command objects of any type. If a new type of command object is created later, it can work with these generic components automatically. For example, in Java, a generic ThreadPool class could have a method addTask(Runnable task) that accepts any object that implements the java.lang.Runnable interface.

1.4     Uses for the command object

Command objects are useful for implementing:

Multi-level undo
   
If all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo() method.
Transactional behavior

Undo is perhaps even more essential when it's called rollback and happens automatically when an operation fails partway through. Installers need this. So do databases. Command objects can also be used to implement two-phase commit.
Progress bars

Suppose a program has a sequence of commands that it executes in order. If each command object has a getEstimatedDuration() method, the program can easily estimate the total duration. It can show a progress bar that meaningfully reflects how close the program is to completing all the tasks.
Wizards

Often a wizard presents several pages of configuration for a single action that happens only when the user clicks the "Finish" button on the last page. In these cases, a natural way to separate user interface code from application code is to implement the wizard using a command object. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses. "Finish" simply triggers a call to execute(). This way, the command class contains no user interface code.
GUI buttons and menu items

In Swing programming, an Action is a command object. In addition to the ability to perform the desired command, an Action may have an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only the Action object.
Thread pools

A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. The items in the queue are command objects. Typically these objects implement a common interface such as java.lang.Runnable that allows the thread pool to execute the command even though the thread pool class itself was written without any knowledge of the specific tasks for which it would be used.
Macro recording

If all user actions are represented by command objects, a program can record a sequence of actions simply by keeping a list of the command objects as they are executed. It can then "play back" the same actions by executing the same command objects again in sequence. If the program embeds a scripting engine, each command object can implement a toScript() method, and user actions can then be easily recorded as scripts.
Networking

It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games.

1.5     Structure




1.1     Participants

 The classes and/or objects participating in this pattern are:


Command  
declares an interface for executing an operation

ConcreteCommand  
-       defines a binding between a Receiver object and an action
-       implements Execute by invoking the corresponding operation(s) on Receiver

Client  
creates a ConcreteCommand object and sets its receiver

Invoker  
asks the command to carry out the request

Receiver  
knows how to perform the operations associated with carrying out the request.


1.2     Typical Usage

The GOF recommend using the Command pattern when you want to:

·         parameterize objects by an action to perform (much like SqlCommands allowing different types of command text and execute methods)
·         specify, queue, and execute requests at different times. Your Command object may live independently of a request
·         support undo. State can be stored on the Command object, and an "undo" operation performs a "reverse" of the execute. For unlimited undo/redo, a list of Commands could be maintained, and one could traverse it backwards or forwards calling "undo" or "execute" appropriately
·         build systems from "primitive or atomic operations" such as transactions


·          

1.3     Sample Code

This code demonstrates the Command pattern which stores requests as objects allowing clients to execute or playback the requests.


class Invoker
  {
    private Command command;

    public void SetCommand(Command command)
    {
      this.command = command;
    }

    public void ExecuteCommand()
    {
      command.Execute();
    }   
  }

abstract class Command
  {
    protected Receiver receiver;

    // Constructor
    public Command(Receiver receiver)
    {
      this.receiver = receiver;
    }

    public abstract void Execute();
  }
class ConcreteCommand : Command
  {
    // Constructor
    public ConcreteCommand(Receiver receiver) : base(receiver)
    { 
    }

    public override void Execute()
    {
      receiver.Action();
    }
  }
class Receiver
  {
    public void Action()
    {
      Console.WriteLine("Called Receiver.Action()");
    }
  }


class MainApp
  {
    static void Main()
    {
      // Create receiver, command, and invoker
      Receiver receiver = new Receiver();
      Command command = new ConcreteCommand(receiver);

      Invoker invoker = new Invoker();
      invoker.SetCommand(command);
      invoker.ExecuteCommand();

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

Output - 

Called Receiver.Action()

1.4     Command Design Pattern in WPF

Windows Presentation Foundation (formerly codenamed "Avalon"), or WPF for short, is a brand new Microsoft framework for developing very rich and powerful Windows applications. It will ship as part of Windows Vista, the next major version of Windows that will be released in the coming months, but WPF will also be available on Windows XP SP2 and Windows Server 2003. There is much to be said about Windows Presentation Foundation and its numerous new and enhanced capabilities, but this article will in stead focus on an old trusted friend, who has finally been given a dedicated room in the big house of Windows User Interface development: the "Command" pattern. This design pattern basically abstracts all actions the user can perform in an application into the notion of "commands"; it has been implemented in many different ways on top of various UI frameworks, but now, it has finally made it into the gut of the system itself. Note that this article is based on a public preview of WPF, so it's possible that there are implementation details that will change over time as the product matures into completion.



Hope this helps.

Thanks & Regards,
Arun Manglick

Thursday, November 18, 2010

Strategy Design Pattern - Behavioural

1.1     Definition


Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
               

1.2     Intent


The strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime.
The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application.

The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

In some programming languages, such as those without polymorphism, the issues addressed by this pattern are handled through forms of reflection, such as the native function pointer or function delegate syntax.

1.3     Motivation


A program that requires a particular service or function and that has several ways of carrying out that function is a candidate for the Strategy pattern. Programs choose between these algorithms based on computational efficiency or user choice. There can be any number of strategies, more can be added, and any of them can be changed at any time.
There are a number of cases in programs where we'd like to do the same thing in several different ways. Some of these are listed in the Smalltalk Companion.

·         Save files in different formats.
·         Compress files using different algorithms
·         Capture video data using different compression schemes.
·         Use different line-breaking strategies to display text data.
·         Plot the same data in different formats: line graph, bar chart, or pie chart.

In each case we could imagine the client program telling a driver module (Context) which of these strategies to use and then asking it to carry out the operation.

The idea behind Strategy is to encapsulate the various strategies in a single module and provide a simple interface to allow choice between these strategies. Each of them should have the same programming interface, although they need not all be members of the same class hierarchy.
However, they do have to implement the same programming interface.

1.4     Applicability


Use the Strategy pattern whenever:
·         Many related classes differ only in their behavior
·         You need different variants of an algorithm
·         An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
·         A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

1.5     Consequences


Strategy allows you to select one of several algorithms dynamically. These algorithms can be related in an inheritance hierarchy, or they can be unrelated as long as they implement a common interface. Since the Context switches between strategies at your request, you have more flexibility than if you simply called the desired derived class. This approach also avoids the sort of condition statements that can make code hard to read and maintain.

On the other hand, strategies don't hide everything. The client code is usually aware that there are a number of alternative strategies, and it has some criteria for choosing among them. This shifts an algorithmic decision to the client programmer or the user.

Since there are a number of different parameters that you might pass to different algorithms, you have to develop a Context interface and strategy methods that are broad enough to allow for passing in parameters that are not used by that particular algorithm.



1.6     Structure


  

1.7     Participants

The classes and/or objects participating in this pattern are:

  • Strategy  (SortStrategy)
    • declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy
  • ConcreteStrategy  (QuickSort, ShellSort, MergeSort)
    • implements the algorithm using the Strategy interface
  • Context  (SortedList)
    • is configured with a ConcreteStrategy object
    • maintains a reference to a Strategy object
    • may define an interface that lets Strategy access its data.            


1.8     Sample Code


This structural code demonstrates the Strategy pattern which encapsulates functionality in the form of an object. This allows clients to dynamically change algorithmic strategies.



class Context
    {
        Strategy strategy;

        public Context(Strategy strategy)
        {
            this.strategy = strategy;
        }

        public void ContextInterface()
        {
            strategy.AlgorithmInterface();
        }
    }
abstract class Strategy
    {
        public abstract void AlgorithmInterface();
    }

class ConcreteStrategyA : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine("ConcreteStrategyA");
        }
    }

class ConcreteStrategyB : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine("ConcreteStrategyB");
        }
    }

class ConcreteStrategyC : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.WriteLine("ConcreteStrategyC");
        }
    }



class MainApp
    {
        static void Main()
        {
            Context context;

            context = new Context(new ConcreteStrategyA());
            context.ContextInterface();

            context = new Context(new ConcreteStrategyB());
            context.ContextInterface();

            context = new Context(new ConcreteStrategyC());
            context.ContextInterface();
        }
    }




1.9     Sample Code 2

This real-world code demonstrates the Strategy pattern which encapsulates sorting algorithms in the form of sorting objects. This allows clients to dynamically change sorting strategies including Quicksort, Shellsort, and Mergesort.



class MySortedList
{
       private ArrayList list = new ArrayList();
       private SortStrategy sortstrategy;

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

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

       public void Sort()
       {
              sortstrategy.Sort(list);

              foreach (string name in list)
              {
                     Console.WriteLine(" " + name);
              }
              Console.WriteLine();
       }
}
    abstract class SortStrategy
    {
        public abstract void Sort(ArrayList list);
    }
    class QuickSort : SortStrategy
    {
        public override void Sort(ArrayList list)
        {
            list.Sort(); // Default is Quicksort
            Console.WriteLine("QuickSorted list ");
        }
    }

class ShellSort : SortStrategy
    {
        public override void Sort(ArrayList list)
        {
            //list.ShellSort(); not-implemented
            Console.WriteLine("ShellSorted list ");
        }
    }
class MergeSort : SortStrategy
    {
        public override void Sort(ArrayList list)
        {
            //list.MergeSort(); not-implemented
            Console.WriteLine("MergeSorted list ");
        }
    }




class MainApp
    {
        static void Main()
        {
            MySortedList studentRecords = new MySortedList ();

            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.Read();
        }
    }

1.10  Sample Code 3

Frequently with applications many of the operations they perform are dynamic depending on several factors. Think about a common scenario, sales tax. Tax amounts are based off the place where you live. There are many different tax rates in each country. A good method of implementing dynamic patterns like taxes is needed. The strategy pattern covers this gap for us.

The strategy pattern is very useful when a dynamic formula or data is needed. In our situation it will allow us to swap out different tax objects when needed. The pattern lets a class take on many different behaviors depending on the context in which it is used.

The strategy patterns starts with an interface that defines the methods that each different behavior defines. Our tax interface is simple, only one method that returns the (full amount of the price) * (the tax amount.).




namespace StrategyPattern
{
    public interface ITaxStrategy
    {
        double CalculateTax(double amount);
    }
}
This interface will be implemented in all of our tax strategy classes to give them a common base.

Two simple classes are then created for calculating taxes for the USA and the UK. Both tax rates are made up, 5% for the USA and 7% for the UK.

namespace StrategyPattern
{
    public class USATax : ITaxStrategy
    {
        public USATax()
        {
        }

        public double CalculateTax(double amount)
        {
            return amount * 1.05;
        }
    }
}

namespace StrategyPattern
{
    public class UKTax : ITaxStrategy
    {
        public UKTax()
        {
        }

        public double CalculateTax(double amount)
        {
            return amount * 1.07;
        }
    }
}

To demonstrate the use of the two classes, we will create a simple inventory item class that represents an item in our stores inventory. The class will just hold the price of the item.

namespace StrategyPattern
{
    public class InventoryItem
    {
        private ITaxStrategy _ItemTax;
        private double _ItemAmount;

        public InventoryItem()
        {
        }

        public void SetTax(ITaxStrategy tax)
        {
            _ItemTax = tax;
        }

        public double ItemAmount
        {
            get { return _ItemAmount; }
            set { _ItemAmount = value; }
        }
        public double ItemWithTax
        {
            get { return _ItemTax.CalculateTax(_ItemAmount); }
        }
    }
}



Now lets examine the code that makes the class use the strategy pattern. A private variable names _ItemTax is declared as type ITaxStrategy. This is our internal representation of which strategy we want the class to use. The SetTax method allows us to set whichever strategy object we need to the inventory item. The property ItemWithTax returns the item's amount with the tax added into it by calling the CalculateTax method on our strategy object.

To see the classes in motion this code can be used.

InventoryItem itm;
itm = new InventoryItem();
itm.ItemAmmount = (double)10;

USATax usaTax;
usaTax = new USATax();

UKTax ukTax;
ukTax = new UKTax();

itm.SetTax(usaTax);
MessageBox.Show(itm.ItemWithTax.ToString());

itm.SetTax(ukTax);            
MessageBox.Show(itm.ItemWithTax.ToString());

The first thing we do is create an object of the InventoryItem class. We then create a US tax object and a UK tax object. After setting the tax object to our inventory class, the message boxes show the result. You will get 10.5 for the first tax and 10.7 for the second showing the different strategies in action.

While this is just a demonstration, in a real world application the tax objects would be created dynamically based on a registry key, configuration file, or based on the findings of a reflection call. One technique I have used is to use reflection to query the install directory for a class that implements the ITaxStrategy interface. When the product is installed, the user chooses what region they are in and the correct dll with the tax class is installed. Reflection can then find this class and create an instance of it on the fly to pass to the inventory class.

1.11  Strategy in MSDN


Both Array and ArrayList provide the capability to sort the objects contained in the collection via the Sort method. In fact, ArrayList.Sort just calls Sort on the underlying array. These methods use the QuickSort algorithm. By default, the Sort method will use the IComparable implementation for each element to handle the comparisons necessary for sorting. Sometimes, though, it is useful to sort the same list in different ways. For example, arrays of strings might be sorted with or without case sensitivity.
To accomplish this, an overload of Sort exists that takes an IComparer as a parameter; IComparer.Compare is then used for the comparisons. This overload allows users of the class to use any of the built-in IComparers or any of their own making, without having to change or even know the implementation details of Array, ArrayList, or the QuickSort algorithm.

Leaving the choice of comparison algorithm up to the user of the class like this is an example of the Strategy pattern. The use of Strategy lets a variety of different algorithms be used interchangeably. QuickSort itself only requires a way to compare objects to each other. By calling Compare through a provided interface, the caller is free to substitute whatever particular comparison algorithm fits its specific needs. The code for the QuickSort can remain unchanged.

Note: In this example, the IComparer interface is implemented using the System.Collections.CaseInsensitiveComparer class to reverse the order of the contents of the ArrayList.




using System;
using System.Collections;

public class SamplesArrayList  {

   public class myReverserClass : IComparer  {

      int IComparer.Compare( Object x, Object y ) 
      {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }

   }

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add( "The" );
      myAL.Add( "quick" );
      myAL.Add( "brown" );
      myAL.Add( "fox" );
      myAL.Add( "jumps" );
      myAL.Add( "over" );
      myAL.Add( "the" );
      myAL.Add( "lazy" );
      myAL.Add( "dog" );

      // Displays the values of the ArrayList.
      Console.WriteLine( "The ArrayList initially contains the following values:" );
      PrintIndexAndValues( myAL );

      // Sorts the values of the ArrayList using the default comparer.
      myAL.Sort();
      Console.WriteLine( "After sorting with the default comparer:" );
      PrintIndexAndValues( myAL );

      // Sorts the values of the ArrayList using the reverse case-insensitive comparer.
      IComparer myComparer = new myReverserClass();
      myAL.Sort( myComparer );
      Console.WriteLine( "After sorting with the reverse case-insensitive comparer:" );
      PrintIndexAndValues( myAL );

   }

   public static void PrintIndexAndValues( IEnumerable myList )  {
      int i = 0;
      foreach ( Object obj in myList )
         Console.WriteLine( "\t[{0}]:\t{1}", i++, obj );
      Console.WriteLine();
   }

}



/*
This code produces the following output.
The ArrayList initially contains the following values:
        [0]:    The
        [1]:    quick
        [2]:    brown
        [3]:    fox
        [4]:    jumps
        [5]:    over
        [6]:    the
        [7]:    lazy
        [8]:    dog

After sorting with the default comparer:
        [0]:    brown
        [1]:    dog
        [2]:    fox
        [3]:    jumps
        [4]:    lazy
        [5]:    over
        [6]:    quick
        [7]:    the
        [8]:    The

After sorting with the reverse case-insensitive comparer:
        [0]:    the
        [1]:    The
        [2]:    quick
        [3]:    over
        [4]:    lazy
        [5]:    jumps
        [6]:    fox
        [7]:    dog
        [8]:    brown
*/



Thanks & Regards,
Arun Manglick

Observer Design Pattern - Behavioural

1.1          Definition

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.          
To achieve this one object (subject) should know about its dependents. Subject maintains list of its dependents. Each dependent who wants to get notification on subject state change, should register with subject.

1.2          Intent

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The observer pattern (sometimes known as Publish/Subscribe) is used in computer programming to observe the state of an object in a program. It is related to the principle of Implicit Invocation.
This pattern is mainly used to implement a distributed event handling system. This is a very interesting feature in terms of real-time deployment of applications.

1.3          Motivation

Observer design pattern has two parts and they are subject and observer. The relationship between subject and observer is one-to-many. In order to reuse subject and observer independently, their relationship can't be tightly coupled.

A practical example is graphical interface toolkits that separate the presentational aspect with application data. The presentation aspect is the observer part and the application data is the observer part.

A spreadsheet program can use the observer pattern as the following:



It also allows multiple number of independent observer objects to register a subject at run time.

1.4          Applicability

Use the observer pattern in any of the following situations:

  • When the abstraction has two aspects with one dependent on the other. Encapsulating these aspects in separate objects will increase the chance to reuse them independently.
  • When the subject object doesn't know exactly how many observer objects it has.
  • When the subject object should be able to notify it's observer objects without knowing who these objects are.

1.5          Structure





1.6          Participants

 The classes and/or objects participating in this pattern are:

·         Subject  (Stock)
o   knows its observers. Any number of Observer objects may observe a subject
o   provides an interface for attaching and detaching Observer objects.
·         ConcreteSubject  (IBM)
o   stores state of interest to ConcreteObserver
o   sends a notification to its observers when its state changes
·         Observer  (IInvestor)
o   defines an updating interface for objects that should be notified of changes in a subject.
·         ConcreteObserver  (Investor)
o   maintains a reference to a ConcreteSubject object
o   stores state that should stay consistent with the subject's
o   implements the Observer updating interface to keep its state consistent with the subject's

1.7          Typical Usage

The typical usages of the observer pattern:

·         Listening for an external event (such as a user action). See Event-driven programming.
·         Listening for changes of the value of a property of an object. Note that often callbacks called in response of a property value change also change values of some properties, so sometimes causing an event cascade.
·         In a mailing list, where everytime an event happens (a new product, a gathering, etc.) a message is sent to the people subscribed to the list.

The observer pattern is also very often associated with the Model-view-controller (MVC) paradigm. In MVC, the observer pattern is used to create a loose coupling between the model and the view. Typically, a modification in the model triggers the notification of model observers which are actually the views.

1.8          Consequences

Further benefit and drawback of Observe pattern include:

·         Abstract coupling between subject and observer
·         Support for broadcast communication. The notification is broadcast automatically to all interested objects that subscribed to it
·         Unexpected updates. Observes have no knowledge of each other and blind to the cost of changing in subject. With the dynamic relationship between subject and observers, the update dependency can be hard to track down



1.9          Sample Code

This code demonstrates the Observer pattern in which registered objects are notified of and updated with a state change.


abstract class Subject
{
  private ArrayList observers = new ArrayList();

  public void Attach(Observer observer)
  {
   observers.Add(observer);
  }

  public void Detach(Observer observer)
  {
       observers.Remove(observer);
  }

  public void Notify()
  {
       foreach (Observer o in observers)
       {
         o.Update();
       }
  }
}
abstract class Observer
{
    public abstract void Update();
}
class ConcreteSubject : Subject
    {
        private string subjectState;

        // Property
        public string SubjectState
        {
            get { return subjectState; }
            set { subjectState = value; }
        }
    }
class ConcreteObserver : Observer
{
  private string name;
  private string observerState;
  private ConcreteSubject subject;

  public ConcreteObserver(ConcreteSubject subject, string name)
  {
       this.subject = subject;
       this.name = name;
  }

  public override void Update()
  {
       observerState = subject.SubjectState;
       Console.WriteLine("Observer {0}'s new state is {1}",
         name, observerState);
  }

  // Property
  public ConcreteSubject Subject
  {
       get { return subject; }
       set { subject = value; }
  }
}

class MainApp
  {
    static void Main()
    {
       // Configure Observer pattern
       ConcreteSubject s = new ConcreteSubject();

       s.Attach(new ConcreteObserver(s, "X"));
       s.Attach(new ConcreteObserver(s, "Y"));
       s.Attach(new ConcreteObserver(s, "Z"));

       // Change subject and notify observers
       s.SubjectState = "ABC";
       s.Notify();

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

Output –

Observer X's new state is ABC
Observer Y's new state is ABC
Observer Z's new state is ABC



1.10       Observer Design Pattern in .NET

The study of design patterns is particularly interesting, as .NET was built with them as a foundation. The Observer pattern seems to appear in many cases throughout the framework.

One of the most visible occurrences of an Observer pattern in .NET is in the implementation of the TraceListener class. Appending individual TraceListener classes to the collection allow them to receive notifications of messages, which can then be consumed. Overriding the default trace listener allows one to write completely customizable code that reacts to a message broadcast from the collection.

Dim myWriter As New TextWriterTraceListener(System.Console.Out)
Trace.Listeners.Add(myWriter)

The trace listener again illustrates the main capabilities of the Observer pattern. The ListenersCollection maintains the master record of the data and broadcasts it to any Observers who have subscribed.

Another example in .NET Framework can be Cache dependency.

In the Cache dependency concept, Cache item validity will depend on the external file or on another cache item.  If a dependency changes, the cache item is invalidated and removed from the cache.  For example, Suppose XML file contains data from which an application reads data and processes and draws different views of graphs.  In such scenarios, applications cache data and will create dependencies on the file from which the data will be read.  Whenever this XML file is updated, Cache data will be removed and the application will reread data and insert again the updated copy of the latest data into the cache.

1.11       Observer Pattern in MSDN

Good object-oriented design emphasizes both encapsulation and loose coupling. In other words, classes should keep internal details private and also minimize their strict dependencies. In most applications, classes don't work in isolation; they interact with many other classes. A common scenario of class interaction occurs when one class (the Observer) needs to be notified when something changes in another (the Subject).

For example, several Windows® Forms controls might need to update their display after a button is clicked. A simple solution would be to have the Subject call a specific method of the Observer whenever a change in state occurs. This introduces a host of problems, however. Now, since the Subject needs to know which method to call, it is tightly coupled to that specific Observer. Furthermore, if you need to add more than one Observer, you have to continue to add code for each method call to the Subject. If the number of Observers changes dynamically, this gets even more complex.

Here, Applying the Observer pattern helps to resolve this problem efficiently. You can decouple the Subject from the Observers so that Observers of any variety can easily be added and removed, at both design time and run time. The Subject maintains a list of interested Observers. Each time the Subject's state changes, it calls the Notify method on each Observer.

While the Gang of Four's Observer pattern solves some of these problems, there are still some roadblocks as below.

·         Subjects must inherit from a specific base class and
·         Also the Observers must implement a special interface – As the Subject (here Subject class in our example) accepts a particular type of Observers (here Observer Interface in our example) in the Attach & Detach methods.

The .NET Framework introduces delegates and events to solve these problems. Events act as the Subject, while delegates act as Observers. Figure 2 shows an example of the Observer pattern, making use of events.

Since EventHandler is a delegate type and not an interface, each Observer doesn't need to implement an extra interface. Assuming it already contains a method with a compatible signature, it only needs to register that method with the event of the Subject. Through delegates and events, the Observer pattern lets you decouple Subjects and their Observers.





Figure 2 Observer Pattern Using Events and Delegates 

public delegate void Event1Hander();
public delegate void Event2Handler(int a);

public class Subject
{
    public Subject(){}

    public Event1Hander Event1;
    public Event2Handler Event2;

    public void RaiseEvent1()
    {
        Event1Handler ev = Event1;
        if (ev != null) ev();
    }

    public void RaiseEvent2()
    {
        Event2Handler ev = Event2;
        if (ev != null) ev(6);
    }
}

public class Observer1
{
    public Observer1(Subject s)
    {
        s.Event1 += new Event1Hander(HandleEvent1);
        s.Event2 += new Event2Handler(HandleEvent2);
    }

    public void HandleEvent1()
    {
        Console.WriteLine("Observer 1 - Event 1");
    }

    public void HandleEvent2(int a)
    {
        Console.WriteLine("Observer 1 - Event 2");
    }
}





Hope this helps.

Thanks & Regards,
Arun Manglick