Observer Pattern Demo : Observer Pattern « Design Patterns « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Design Patterns » Observer PatternScreenshots 
Observer Pattern Demo
 

using System;
public delegate void ChangedEventHandler(object sender, EventArgs e);

public class Subject {

    private string data;
    public event ChangedEventHandler Changed;

    public string Data {
        get return data; }
        set {
            data = value;
            this.OnChanged(EventArgs.Empty);
        }
    }

    protected virtual void OnChanged(EventArgs e) {
        if (Changed != null)
            this.Changed(this, e);
    }

    public Subject() { }
}


public class Observer {
    private Subject data;
    private string observerName;

    public Subject ObservedObject {
        get return data; }
        set data = value; }
    }

    private void DataChanged(object sender, EventArgs e) {
        Console.WriteLine("Notification to {0}, {1}", observerName, data.Data);
    }

    public void Attach() {
        data.Changed += new ChangedEventHandler(DataChanged);
    }

    public void Detach() {
        data.Changed -= new ChangedEventHandler(DataChanged);
    }

    public Observer(string name) {
        observerName = name;
    }
}

class Client {
    static void Main(string[] args) {
        Subject sub = new Subject();
        Observer observerA = new Observer("A Observer");
        Observer observerB = new Observer("B Observer");
        observerA.ObservedObject = sub;
        observerB.ObservedObject = sub;
        observerA.Attach();
        observerB.Attach();
        sub.Data = "1";
        observerA.Detach();
        sub.Data = "2";
    }
}

 
Related examples in the same category
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.