5,666,132 members and growing! (13,534 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

Design Patterns - Observer Pattern

By Islam ElDemery

Explains the observer pattern and simple implementation
C#

Posted: 24 Jan 2008
Updated: 25 Jan 2008
Views: 4,074
Bookmarked: 5 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
10 votes for this Article.
Popularity: 2.65 Rating: 2.65 out of 5
3 votes, 30.0%
1
3 votes, 30.0%
2
1 vote, 10.0%
3
1 vote, 10.0%
4
2 votes, 20.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article
Introduction
This article explains the Observer patterns which is one of the C# Design Patterns, the article provides a very simple implementation so its complexity can be easily understood. The observer pattern makes an object that if its state changed somehow, other instances will be notified (or updated) automatically.
observer From dofactory.com
Implementation
Imagine if we have cards game, some tables, and some players.. On a table.., in the game context the suit of cards is changed time by time and we want to notify the players each time the suit is changed. Note* this is not a complete logic for a cards game, its an example. The player object is going to have a function Update() which will be called by the notifier, and data:
  • Player Number (Player Identity) int
  • Current Suit string
  • Current Table Object Table
How can the player be notified? we pass the (always changes) object of the table as a parameter in the Update() function, So the player (object) can see the new differences in the table (object). This is the Player object..
    interface IPlayer
    {
        void Update(Table _table);
    }

    class Player : IPlayer
    {

        public void Update(Table _table)
        {
            this._table = _table;
            _currentSuit = _table.currentSuit;
            Console.WriteLine("Player '" + _PlayerNo + "' notified that current suit is " + _currentSuit);
        }

        private int _PlayerNo;
        private Table _table;
        private string _currentSuit;

        public Player(int _PlayerNo)
        {
            this._PlayerNo = _PlayerNo; 
        }

        public Table CurrentTable 
        { 
            get { return _table; } 
        }

    }

In our table object you want to add players or remove players (or count them for some reasons..) So in the table object you'll have:
  • An array list of the players objects List< Player >
  • Current Suit string
  • Table Number int
  • Add Player Function AddPlayer()
  • Remove Player Function RemovePlayer()
  • Notify Function Notify()
The notify function is sending the updated object (table) to all players objects..
    abstract class Table
    {
        private string _currentSuit;
        private int _tableNo;
        private List< Player > players = new List< Player >();

        public Table(int _tableNo, string _currentSuit)
        {
            this._tableNo = _tableNo;
            this._currentSuit = _currentSuit;
        }
        public void AddPlayer(Player _player)
        {
            players.Add(_player);
        }

        public void RemovePlayer(Player _player)
        {
            players.Remove(_player);
        }

        public string currentSuit
        {
            get { return _currentSuit; }
            set
            {
                _currentSuit = value;
                Notify();
            }
        }

        public void Notify()
        {
            foreach (Player _player in players)
            {
                _player.Update(this);
            }
        }
    }

    class ReadyTable : Table
    {
        public ReadyTable(int _tableNo, string _currentSuit) : base(_tableNo, _currentSuit)
        { }
    }

And the Main()
    class Program
    {
        static void Main(string[] args)
        {
            //Create Table
            //specify a table id and a starting suit
            ReadyTable table = new ReadyTable(1, "Spade");
            Console.WriteLine("Starting table 1 with suit spades, suit will be changing in 3 seconds");

            //Create Players
            List< Player > players = new List< Player >(4);//specify number of players
            for (int i = 0; i < 4; i++)
            {
                players.Add(new Player(i));
                //add players to the table
                table.AddPlayer(players[i]);
            }

            Thread.Sleep(3000);
            //Change the suit and all players will be notified
            table.currentSuit = "Hearts";

            Thread.Sleep(6000);
            table.currentSuit = "Diamonds";

            Console.ReadLine();
        }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Islam ElDemery


Blog

Occupation: Web Developer
Location: Egypt Egypt

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 14 of 14 (Total in Forum: 14) (Refresh)FirstPrevNext
GeneralEventsmemberSteve Hansen20:44 24 Jan '08  
GeneralRe: EventsmemberIslam ElDemery0:13 25 Jan '08  
GeneralA class diagram is needed..memberNirosh16:48 24 Jan '08  
GeneralRe: A class diagram is needed..memberIslam ElDemery0:08 25 Jan '08  
GeneralI am sorry to say this...memberNirosh0:48 25 Jan '08  
GeneralRe: I am sorry to say this...memberIslam ElDemery1:13 25 Jan '08  
GeneralRe: I am sorry to say this...memberNirosh4:32 25 Jan '08  
GeneralRe: I am sorry to say this...memberIslam ElDemery4:38 25 Jan '08  
GeneralI know the place...memberNirosh4:38 25 Jan '08  
GeneralRe: I know the place...memberIslam ElDemery4:42 25 Jan '08  
GeneralRe: I know the place...memberNirosh4:43 25 Jan '08  
GeneralRe: I know the place...memberIslam ElDemery4:49 25 Jan '08  
GeneralRe: I am sorry to say this...memberRavi Bhavnani2:33 25 Jan '08  
GeneralRe: I am sorry to say this...memberNirosh4:11 25 Jan '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 25 Jan 2008
Editor:
Copyright 2008 by Islam ElDemery
Everything else Copyright © CodeProject, 1999-2008
Web19 | Advertise on the Code Project