观察者模式
定义
//定义动物接口 public interface IAnimal { /// <summary> /// 动物名称 /// </summary> public string _Name { get; set; } /// <summary> /// 动物行动 /// </summary> void Action(); } //定义猫(观察者) public class Cat : IAnimal { public string _Name { get; set; } public Cat(string Name) { _Name = Name; } public void Action() { Console.WriteLine($"小猫{_Name}开始跑"); } } //定义狗(观察者) public class Dog : IAnimal { public string _Name { get; set; } public Dog(string Name) { _Name = Name; } public void Action() { Console.WriteLine($"小狗{_Name}开始叫"); } } //定义主人(定义为单例) public class Owner { //事件 public event Action? OwnerEvent; private static Owner? _ownerSlgtion; private static readonly object _lock = new object(); private Owner() { OwnerEvent = new Action(() => { Console.WriteLine("事件初始化"); }); } public static Owner GetOwner() { if (_ownerSlgtion == null) { lock (_lock) { if (_ownerSlgtion == null) { _ownerSlgtion = new Owner(); } } } return _ownerSlgtion; } public void Action() { Console.WriteLine("主人回来了"); OwnerEvent?.Invoke();//触发事件 } }
调用
Console.WriteLine("观察者模式"); Cat cat1 = new Cat("Jim"); Dog dog1 = new Dog("Tom"); Owner owner1 = new Owner(); //事件不能在类外部进行初始化,而委托可以 //事件是一种特殊委托类型的实例 //事件更安全 //事件是为了当类内部变化时能通知类的外部 //订阅事件 owner1.OwnerEvent += cat1.Action; owner1.OwnerEvent += dog1.Action; owner1.Action();
喜欢 C#、SQL、Web