Observer pattern with .net

Hi folks,

Well I am investigating design patterns by reading an article so after reading a bit I thought it would be nice if I write some code and test it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleApplication1
    {
    class Program
    {
    /// <summary>
    /// Product Class
    /// </summary>
    public class Product
    {
    public delegate void NameChangeEventHandler(int a);
    public event NameChangeEventHandler NameChanged;
    private string _name;
    public string Name
    {
    get
    {
    return _name;
    }
    set
    {
    _name = value;
    if (NameChanged != null)
    {
    NameChanged(5);
    }
    }
    }

    public Product(string name)
    {
    Name = name;
    }
    public void PrintName()
    {
    Console.WriteLine("ProductName={0}", Name);
    }
    }

    /// <summary>
    /// Test Class
    /// </summary>
    public class Test
    {
    public Test(Product P)
    {
    P.NameChanged += new Product.NameChangeEventHandler(ChangeDetected);
    }
    public void ChangeDetected(int a)
    {
    Console.WriteLine("change found,argument passed is {0}",a);
    }

    }

    static void Main(string[] args)
    {
    Product p = new Product("najam awan");
    p.PrintName();
    Test t = new Test(p);
    p.Name = "najaf awan";
    p.PrintName();
    Console.ReadKey();

    }
    }
    }
comments powered by Disqus