# 观察者模式

属于行为型模式。
它定义了一种一对多的依赖关系,当一个对象的状态发生改变时,其所有依赖者都会收到通知并自动更新。

CSharp 事件就是观察者模式。接下来的演示将不会使用委托和事件,而是使用接口来实现。

# 类图

img

# 代码

# 观察者接口以及实现接口的类

namespace BehavioralPatterns_ObserverPattern
{
    /// <summary>
    /// 观察者
    /// </summary>
    public interface Observer
    {
        /// <summary>
        /// 更新
        /// </summary>
        public void Update();
    }
}
namespace BehavioralPatterns_ObserverPattern
{
    /// <summary>
    /// 形状
    /// </summary>
    public class Shape : Observer
    {
        public string ShapeName;
        public string ColorName;
        public Shape(string shapeName, string colorName)
        {
            ShapeName = shapeName;
            ColorName = colorName;
        }
        public void Show()
        {
            Console.WriteLine("Shape:" + ShapeName);
            Console.WriteLine("Color:" + ColorName);
        }
        public void Update()
        {
            ShapeName = "Default";
            ColorName = "Default";
        }
    }
}

# 被观察者

namespace BehavioralPatterns_ObserverPattern
{
    public class ObserverAction
    {
        /// <summary>
        /// 观察者列表
        /// </summary>
        private List<Observer> ObserverList;
        public ObserverAction()
        {
            ObserverList = new List<Observer>();
        }
        /// <summary>
        /// 添加观察者
        /// </summary>
        /// <param name="listener"></param>
        public void AddObserver(Observer observer)
        {
            ObserverList.Add(observer);
        }
        /// <summary>
        /// 移除观察者
        /// </summary>
        /// <param name="listener"></param>
        public void RemoveObserver(Observer observer)
        {
            ObserverList.Remove(observer);
        }
        /// <summary>
        /// 通知所有观察者
        /// </summary>
        public void Invoke()
        {
            foreach (var item in ObserverList)
            {
                item.Update();
            }
        }
    }
}

# 测试

namespace BehavioralPatterns_ObserverPattern
{
    public class Program
    {
        private static void Main()
        {
            Shape shape = new Shape("Square", "Red");
            ObserverAction observerAction = new ObserverAction();
            observerAction.AddObserver(shape);
            shape.Show();
            observerAction.Invoke();
            Console.WriteLine();
            shape.Show();
        }
    }
}

运行结果:
Shape:Square
Color:Red

Shape:Default
Color:Default