次の方法で共有


Design pattern : Observer pattern

Definition

A way of notifying dependent classes of changes.

The Observer pattern defines a one to many relationships between objects so that when one changes its state, all the others are notified accordingly.

Encapsulate the core components in a Subject abstraction, and the variable components in an Observer hierarchy.

Design

The Observer pattern is composed of two classes. The Subject/Target is a class whose objects change their state at an independent rate. Observers may indicate that they wish to be informed of these changes so the Subject/Target will send them notifications.

Code

//Notifier

    public delegate void ChangedEventHandler(object sender);

    //Subject

    public class Temperature

    {

        public event ChangedEventHandler Changed;

private int _temperaturevalue;

       Public TemperatureValue

{

get {return _temperaturevalue;}

set(object value)

{    if( changed!=null) { changed( this) }

         _temperaturevalue=value;

}

}

}    public class ObserverOne
    {
        public ObserverOne(Temperature temperature)
        {
            Temperature.Changed += new ChangedEventHandler(A);
        }
        public void A(object sender, ChangedEventArgs e)
        {
     
     Console.WriteLine("Temperature modified ");

               }
    }

    public class ObserverTwo
    {
        public ObserverTwo(Temperature temperature )
        {
            Temperature .Changed += new ChangedEventHandler(A);
        }

        public void A(object sender, ChangedEventArgs e)
        {
              Console.WriteLine("Temperature modified ");

        }
    }
//Client
static void Main(string[] args)
        {
            Temperature temperature = new Temperature ();

            ObserverOne observer1 = new ObserverOne(temperature );
            ObserverTwo observer2 = new ObserverTwo(temperature );

            Temperature .TemperatureValue=100;

        }

 

Result : As soon as the TemperatureValue property is changed it will notify the changes to the both observerone and observertwo .