google analytics

Tuesday, September 7, 2010

Observer Pattern - implementation and application with C#.NET

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 ObserverPatter
{
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 ObserverPatter
{
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 ObserverPatter
{
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 ObserverPatter
{
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 ObserverPatter
{
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 ObserverPatter
{
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

Sunday, June 6, 2010

Git in Windows with TortoiseGIT client & ProjectLocker free Git Hosting

Hello All

Hope you all are fine. Today I will show how to work with Git in windows environment with TortoiseGIT client & ProjectLocker Git Hosting. ProjectLocker is a good Git hosting provider for startup a private project, you may check there pricing plan to let know more about the features of different plan.

Now first do signup from https://www.projectlocker.com/signup/startup ( I will show through a free plan) , After signing up verify your account and login through https://portal.projectlocker.com/ . You will find “Account Links > Add Project” from the left menu panel, select “Add Project”. Now give a project name, description and select Git as Repository type.I’m giving the name “DemoGit” for my project.Click “Create Project”.

In the next step you have to create user account from “Account Links > Add User”. Now you have to create a Public Key for your repository.

First download PuttyGen from the [ link ] or anywhere you found through googling and create a public and private key pair through the software as bellow by clicking Generate button and moving mouse pointer arbitrary.

Now give a passphrase and confirm it.After that save the private key by clicking “Save private key” , I have saved my with the name demokey.ppk . You have to copy the public key (the top red marked block in the following pictuer)

Its time to get back in ProjectLocker :) .  Click manage public key from “User Links > Manage Public Keys” and click “New Key”. Then pest  the public key in Key section ,User name (which you have created in user section, I’m putting my email here) and a name to identify the key in Name section and save it as bellow by clicking “Save Public Key”:

Open list projects from “Account Links > List Projects” and select your desired project from the Name column (I’m selecting DemoGit for the demonstration purpose.) as bellow:

Now assign the user to the project from the user list bellow by clicking “Add To Project” corresponding user.

It’s the time to play with Git client software. For this, first we have to install  msysgit from http://code.google.com/p/msysgit/downloads/list after that TortoisGIT from http://code.google.com/p/tortoisegit/downloads/list accordingly with next,next flow (I mean default settings, you don’t have to change any settings over there ) and reboot your machine.

Now open a folder where you want to put your files to sink with Git repository (I’m opening a folder named “DemoGit”). After that right click on the the folder and click “Gil Clone..” as bellow:

Now in the next panel you have to pest the Url (git repository location , you will get it from “User Links > User Home” like the image bellow ) and locate the private key which we have generated earlier (for me its demokey.ppk)

Now you have to enter passphrase which you have set during key generation.

That’s it , we have successfully configured our repository with TortoiseGIT client.

Now we will add a file named “demo_text_file.txt” and it to our repository.To that we have to right click the folder again and do as per image bellow.

Then confirm the add operation :

Now you have to do as per following image sequence to push the fine into server.

We are going to change some text in our file and give Git Commite as per image bellow:

We have to put a message before committing something into our brunch in Message section, We also can put signed off signature as bellow:

To finally push the file into server we have to click push :

And the we have to select in which brunch we should to push in server and click ok.

No to sink with others commit we have to update the code base as bellow.

Then select “Pull” as bellow:

There are lots more Git operation we can perform through TortoiseGIT but in this tutorial I just have shown how to do the basic operation. Hope in future I will post more advance feature & operation of GIT. 

Thanks

That’s all for today .

To know more visit to my blog [ http://blog.actcode.com/ ]

Bye

Sunday, May 16, 2010

PHP overloading ( method overloading and property overloading)

Hello All

Today I will focus on overloading method and property in PHP. Unlike other language Java/C# overloading is working in a little bit different way for PHP.

Normally we can overload a method by providing different/varying argument(s) ,but in PHP it should have to create through some magic methods.

These magic methods are as bellow:

(For overloading property)

void __set ( string $name , mixed $value )

mixed __get ( string $name )

bool __isset ( string $name )

void __unset ( string $name )

(For overloading method)

mixed __call ( string $name , array $arguments )

mixed __callStatic ( string $name , array $arguments )

It will be better to describe the operation inside code comment rather that bookish thing hear. Please go through the code comment to get know what is gonging over there to perform overloading .

<?php
class PhpOverloading {
  
  /* Property overloading -start- */
  private $_data = array ();
  
  public function __set($name, $value) {
    /*
     * set the key value in the $_data private
     * variable.
     * */
    $this->_data [$name] = $value;
  }
  
  public function __get($name) {
    /*
     * Retrieve the value of key which we have
     * set through __set method.
     * */
    return $this->_data [$name];
  }
  
  public function __isset($name) {
    /*
     * Check wheather the key exist or not. 
     * */
    return isset ( $this->_data [$name] );
  }
  
  public function __unset($name) {
    /*
     * Unset the value of key.
     * */
    unset ( $this->_data [$name] );
  }
  
  /* Property overloading -end- */
  
  /* Method overloading -start- */
  public function __call($name, $argument) {
    /*
     * perform your operation as needed,
     * I just used a switch case to show how 
     * we can set the dynamic method with parameters.
     * */
    
    switch ($name) {
      case ('First') :
        echo "This is the first dyanamic method and arguments are " . implode ( ',', $argument );
        break;
      case ('Second') :
        echo "2nd method and the arguments are {$argument[1]} and {$argument[2]}";
        break;
      default :
        echo "Method unhandled with the name {$name} and arguments are " . implode ( ',', $argument );
    }
  }
  
  public static function __callstatic($name, $argument) {
    
    /*
     * It's similar as __call but works as static method
     * call. 
     * */
    switch ($name) {
      case ('FirstStatic') :
        echo "Static first dyanamic method and arguments are " . implode ( ',', $argument );
        break;
      case ('SecondStatic') :
        echo "Static 2nd method and the arguments are {$argument[1]} and {$argument[2]}";
        break;
      default :
        echo "Static method unhandled with the name {$name} and arguments are " . implode ( ',', $argument );
    }
  }
  
/* Method overloading -end- */
}
$phpOverloading = new PhpOverloading ();
echo 'Property overloading output -start-';
echo "<br /><br />";
var_dump ( isset ( $phpOverloading->dynamicProperty ) );
$phpOverloading->dynamicProperty = "new property injected";
echo "<br />";
echo $phpOverloading->dynamicProperty;
echo "<br />";
var_dump ( isset ( $phpOverloading->dynamicProperty ) );
unset ( $phpOverloading->dynamicProperty );
echo "<br />";
var_dump ( isset ( $phpOverloading->dynamicProperty ) );
echo "<br /><br />";
echo 'Property overloading output -end-';
echo "<br /><br />";
echo 'Method overloading output -start-';
echo '<br /><br />';
$phpOverloading->First ( 'one', 'two', 'three' );
echo "<br />";
$phpOverloading->Second ( '1', '2' );
echo "<br />";
$phpOverloading->UnHandledMethod ( '1', '2' );
echo "<br /><br />";
echo 'staic method overloading';
echo "<br /><br />";
PhpOverloading::FirstStatic ( 'one', 'two', 'three' );
echo "<br />";
PhpOverloading::SecondStatic ( '1', '2' );
echo "<br />";
PhpOverloading::UnHandledStaticMethod ( '1', '2' );
echo "<br /><br />";
echo 'Method overloading output -end-';
/*
 * final output is as bellow:
 
Property overloading output -start-
bool(false) 
new property injected
bool(true) 
bool(false) 
Property overloading output -end-
Method overloading output -start-
This is the first dyanamic method and arguments are one,two,three
2nd method and the arguments are 2 and 
Method unhandled with the name UnHandledMethod and arguments are 1,2
staic method overloading
Static first dyanamic method and arguments are one,two,three
Static 2nd method and the arguments are 2 and 
Static method unhandled with the name UnHandledStaticMethod and arguments are 1,2
Method overloading output -end-
 * 
 * */

You may check my other posts from my [ Blog ] .

Please provide your feedback.

Thanks

That's all for today.

BYE