C# 设计开发模式 -观察者模式

①定义一个要被监视的对象

 1 class TestClass
 2     {
 3         private string value;
 4         public string Value
 5         {
 6             get { return value; }
 7 
 8             set
 9             {
10                 this.value = value;
11                 Notify();
12             }
13         }
14 
15         public event EventHandler<TestClass> ValueChanged;
16 
17         private void Notify()
18         {
19             if (ValueChanged != null)
20             {
21                 ValueChanged(this, this);
22             }
23         }
24 
25     }
View Code

②观察者订阅该事件

 1 Program.testClass.ValueChanged += testClass_ValueChanged; 

③在事件处理程序中处理相关逻辑

 1 this.textBox1.Text = Program.testClass.Value; 

posted on 2016-11-14 11:34  Joey.ZJ  阅读(133)  评论(0编辑  收藏  举报