Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C#

Illustrated GOF Design Patterns in C# Part V: Behavioral II

Rate me:
Please Sign up or sign in to vote.
4.87/5 (19 votes)
31 Mar 2003CPOL9 min read 136.1K   496   173  
Part V of a series of articles illustrating GOF Design Patterns in C#
//	example of implementing the Observer pattern

using System;
using	System.Collections;
using	Concrete;

namespace	Concrete
{
	public delegate void	PriceChanged(BaseProduct p);

	public class	BaseProduct
	{
		private static int	m_nIDPool = 1;
		private int	m_nID;
		private string	m_strName;
		private double	m_yPrice;

		public event PriceChanged	PriceChangedObservers;

		public BaseProduct(string name, double price)
		{
			m_nID = m_nIDPool++;
			m_strName = name;
			m_yPrice = price;
		}

		public int	id	{	get	{	return m_nID;	}	}

		public string	name
		{
			get	{	return m_strName;	}
			set	{	m_strName = value;	}
		}

		public double	price
		{
			get	{	return m_yPrice;	}
			set
			{
				m_yPrice = value;

				//	notify listeners
				PriceChangedObservers(this);
			}
		}
	}

	public class	BaseObserver
	{
		virtual public void OnPriceChanged(BaseProduct p)
		{
			Console.WriteLine("{0} detected price change on {1}, ${2}",
				this.GetType().ToString(), p.name, p.price);
		}

		public void	ObserveProduct(BaseProduct p)
		{
			p.PriceChangedObservers += new PriceChanged(this.OnPriceChanged);
		}
	}

	public class	POObserver : BaseObserver
	{
		override public void	OnPriceChanged(BaseProduct p)
		{
			base.OnPriceChanged(p);
			Console.WriteLine("{0} updating PO pricing", this.GetType().ToString());
		}
	}

	public class	UIObserver : BaseObserver
	{
		override public void	OnPriceChanged(BaseProduct p)
		{
			base.OnPriceChanged(p);
			Console.WriteLine("{0} updating UI view", this.GetType().ToString());
		}
	}
}

namespace	Client
{
	public class	TheClient
	{
		public static void	Main(string[] args)
		{
			BaseProduct	p1 = new BaseProduct("Product A", 14.99);
			BaseProduct	p2 = new BaseProduct("Product B", 9.99);
			UIObserver	ui = new UIObserver();
			POObserver	po = new POObserver();

			ui.ObserveProduct(p1);
			ui.ObserveProduct(p2);
			po.ObserveProduct(p1);
			po.ObserveProduct(p2);

			p1.price = 24.99;
			p2.price = 11.99;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Chief Technology Officer
United States United States
20+ years as a strategist at the intersection of business, design and technology.

Comments and Discussions