[原创] 利用OBserve模式实现相关类的事件自动处理

OBserve模式一般用来对一个特定的主体subject进行观察,当subject中的数据发生变化时,其他注册到subject中的observe中的相应时间会自动的进行处理。在应用中,主要表现在winforms的控件设计中,做为一个subject,其中发生变化之后,它的obrserve对象们会根据这个变化自动来完成自身的更新,而相互间不发生关系。应用该模式,可以做到界面与事件处理的分离,保持界面元素代码的清晰。
下面是一个利用该模式的测试例子。


subject.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Forms;

namespace WindowsApplication2
{
    
//定义一个subjct的接口,仅仅为了保持程序的可读性和整体性
    public interface  Isubject
    
{
    }

    
//定义一个observe接口,用于观察主体
    public interface IObserve
    
{
        Isubject subject
        
{
            
set;
        }

       
    }

    
//定义主体对象,实现Isubject接口
    public class MYSubject : Isubject
    
{
        
//定义事件和委托
        public virtual event MyEventHandler MyEvented;
        
public delegate void MyEventHandler(object Object, EventArgs args);
        
public string SetString;
       
        
//根据实际需要激活事件
        public void SetEvent(string str)
        
{
            SetString 
= str;
            MessageBox.Show(str);
           
if(MyEvented !=null)
               MyEvented(
this, EventArgs.Empty);
           
        }

    }

    
//定义观察者类,实现IObserve接口
    public class MyObserver : IObserve
    
{
        
IObserve 成员
    }

}


在主程序中的调用:

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication2
{
    
public partial class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();
        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            MYSubject sub 
= new MYSubject();
            MyObserver obj 
= new MyObserver();
            obj.subject 
= sub;
            sub.SetEvent(
"Only A Test!");
            sub.SetEvent(
"The second Test!");
        }

    }

}

这样,当sub数据发生变化之后,observe中的相应事件也会自动被更新,可以自动完成自身数据的修改和内容的显示。

posted on 2006-04-20 10:30  c#之旅  阅读(551)  评论(0编辑  收藏  举报

导航