Archive for the ‘UML’ Category

Hello All

Today I will go through with “Observer Patter”, where I will try to explain a simple example of this pattern as well as implementation and use.

First come to what is Observer Patter, as per Wikipedia the general definition of Observer pattern is as bellow:

The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

The UML diagram of basic observer pattern is as bellow:

clip_image002

How actually this pattern works?

Well as per the above definition we have 2 types of objects one is Subject and other one is Observer. A Subject maintain a list of Observe objects and notify those when property of subject changes.

Example:

Suppose we are maintaining stock exchanges data and we have number of securities agencies. Those securities consume our stock’s data as per there need. When they what to consume data, they register in our system and unsubscribe when they are needed. Here the catch is, they are always updated for each stock’s data change.

In the following C# code example I will try to pull out the gist of Observer pattern as per our above description.

In the code example I have taken 2 interfaces and 3 concrete classes of which 1 interface and 2 concrete classes are of Observer’s & 1 interface and 1 concrete class of Subject’s.

IObserver Interface:

This interface contains 2 method signatures. One is Update and another is ShowData.

using System.Collections.Generic;
namespace ObserverPattern
{
 interface IObserver
  {
 void Update(Dictionary<string, float> stocks);
     void ShowData();
  }
}
FirstObserver concrete class:

This class implements the IObserver interface. The Update method changes the property of stocks information with the new stocks information and ShowData makes the new stock information visible.

using System;
using System.Collections.Generic;
namespace ObserverPattern{
  class FirstObserver : IObserver
   {
 private Dictionary<string, float> _stocks;
      public void Update(Dictionary<string, float> newData)
      {            this._stocks = newData;
       this.ShowData();
      }
  public void ShowData()
       {            Console.WriteLine("First Securities LTD");
        foreach( KeyValuePair<string,float> data in _stocks)
        {
            Console.WriteLine("Current price of {0} is now {1}",data.Key,data.Value);
        }
       }
   }
}
SecondObserver concrete class:

This class is also act as previous one. We are taking this class just to show as second observer which will be a subscriber of the server and will  be unsubscribe latter.


using System;
using System.Collections.Generic;
namespace ObserverPattern
{
 class SecondObserver : IObserver
    {
      private Dictionary<string, float> _stocks;  

      public void Update(Dictionary<string, float> newData)
      {
       this._stocks = newData;
       this.ShowData();
     }

   public void ShowData()
    {
         Console.WriteLine("Second Securities LTD");
         foreach (KeyValuePair<string, float> data in _stocks)
         {
           Console.WriteLine("Current price of {0} is now {1}", data.Key, data.Value);
          }
     }
 }
}

ISubject Interface:

This interface contains 3 main method’s  signature 1.RegisterObserver 2.RemoveObserver 3.NotifyObservers

RegisterObserver method register an observe in subject’s observer list.

RemoveObserver method unregister an observer from the subject’s observer list.

NotifyObservers method is responsible to notify all objects which are subscribed to the server .

namespace ObserverPattern
{
  interface ISubject
  {
     void RegisterObserver(IObserver o);
     void RemoveObserver(IObserver o);
     void NotifyObservers();
   }
}

StockSubject concrete class:

We have implemented ISubject interface in this class and proceeded accordingly.
using System.Collections.Generic;
namespace ObserverPattern
{
class StockSubject : ISubject
   {
 private List<IObserver> _observers = new List<IObserver>();
 private Dictionary<string, float> _stocks;
public void RegisterObserver(IObserver o)
 {
 _observers.Add(o);
        }
public void RemoveObserver(IObserver o)
 {
_observers.Remove(o);
 }
 public void NotifyObservers()
{
foreach(IObserver observer in _observers)
 {
 observer.Update(_stocks);
 }
 }
 public void setStockPriceInformation(Dictionary<string,float> newData)
 {
 this._stocks = newData;
 this.NotifyObservers();
 }
}
}
Now in the runner class “Program” we have implemented our application where we have added two observers and letter removed one observer at runtime.
using System;
using System.Collections.Generic;
namespace ObserverPattern{
 class Program
  {
static void Main(string[] args)
 {
StockSubject stockSubject = new StockSubject();
 var firstObserver = new FirstObserver();
 var secondObserver = new SecondObserver();
stockSubject.RegisterObserver(firstObserver);
 stockSubject.RegisterObserver(secondObserver);
            var dataSet = new Dictionary<string,float>();
  dataSet.Add("Google Inc", 500.25f);
  dataSet.Add("Micorsoft",400.15f);
 stockSubject.setStockPriceInformation(dataSet);
  dataSet.Clear();
dataSet.Add("Google Inc", 330.25f);
 dataSet.Add("Micorsoft", 550.15f);
 stockSubject.RemoveObserver(secondObserver);
 stockSubject.setStockPriceInformation(dataSet);
Console.ReadKey();
 }
 }
}
Output :
 
output 
Ok that’s it for today . Let me know if you have any concern regarding this pattern or code.
 
Take care
Bye

Hello All

Today I will go through with UML class diagram. It’s like old wine in old bottle ;) . We all know that these are very basic but now a days people just stat to do coding without making any class or activity diagram, so eventually they fall in a design related issue if the system becomes huge.

Again UML is more impotent to understand any complex system which is properly documented in UML diagram.UML makes our life simple through notifying us the design fault.

So let’s start the old song again.

Class:

Generally there are 3 components in the class icon as following.

1. Class Name

2. Attributes

3. Functions / Methods

Visibility:

Visibility of class diagram represents the accessibility of the class members. Visibility notations are as bellow .

Notations

Access type

-

Private

+

Public

~

Protected

Association:

When two objects are connected with each other then it can be represent as association. For students and seminar we can use association notation where students are attending in seminar.

Multiplicity Indicators:

Multiplicity indicates the countable objects relation with other objects.

Indicator

Meaning

0..1

Zero or one

1

One only

0..*

Zero or more

1..*

One or more

n

Only n (where n > 1)

0..n

Zero to n (where n > 1)

1..n

One to n (where n > 1)

Composition:

Composition represents with a black diamond. It represents that a component strongly depends on another component. Suppose we have two objects one is circle and another is point. In that case a circle consists of many points.

Aggregation:

When an object form with another object(s) but not mandatory to form the main object then its denoted by a diamond. Suppose student and school object can represent with aggregation relationship.

Inheritance:

When one object inherits property from any parent object then the sign denoted with a triangle shape arrow.

Thanks

That’s all for the day.
BYE

User ScrumPad for your Agile based projects.