观察者模式

using System;
using System.Collections;
using System.Collections.Generic;

namespace Observer
{
    public interface IObserver
    {
        void Update(Object obj);
    }
    public interface IObservable
    {
        void Register(IObserver anObserver);
        void UnRegister(IObserver anObserver);
        void NotifyObservers(Object obj);
    }

    public class People : IObservable
    {
        private string m_name;
        public string Name
        {
            get
            {
                return m_name;
            }
            set
            {
                m_name = value;
            }
        }
        private int m_age;
        public int Age
        {
            get
            {
                return m_age;
            }
            set
            {
                m_age = value;
                NotifyObservers(m_age);
            }
        }

        public void Print()
        {
            Console.WriteLine("Name:" + m_name + " Age:" + m_age);
        }

        #region Observer
        private Hashtable m_observers;
        public People()
        {
            m_observers = new Hashtable();
        }
        public void Register(IObserver anObserver)
        {
            m_observers.Add(anObserver,anObserver);
        }
        public void UnRegister(IObserver anObserver)
        {
            m_observers.Remove(anObserver);
        }
        public void NotifyObservers(Object obj)
        {
            foreach (IObserver observer in m_observers.Values)
            {
                observer.Update(obj);
            }
        }
        #endregion
    }
    public class UI : IObserver
    {
        public void Update(Object obj)
        {
            Console.WriteLine("年龄:" + obj);
            if(obj.GetType() == typeof(int))
            {
                Console.WriteLine("年龄:" + obj);
            }
        }
    }
    public class MainClass
    {
        public static void Main()
        {
            Console.WriteLine("Hello World");

            People people = new People();
            people.Name = "Lily";
            people.Age = 18;
            people.Print();

            UI ui = new UI();
            people.Register(ui);
            people.Print();
            people.Age = 20;
            people.Print();

            people.UnRegister(ui);
            people.Age = 22;
            people.Print();

        }
    } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值