定义
public interface IAnimal { public string _Name { get; set; } 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 delegate void DelegateAction(); public class OwnerDelegate { public void Action() { Console.WriteLine("主人回来了"); } public OwnerDelegate() { delegateAction = new DelegateAction(Action); } public DelegateAction delegateAction; public void AddAction(DelegateAction action) { delegateAction += action; } public void RemoveAction(DelegateAction action) { if (delegateAction != null) { delegateAction -= action; } } public void Update() { delegateAction.Invoke(); } } public class Owner { public List<IAnimal> animals = new List<IAnimal>(); public void Addanimal(IAnimal animal) { animals.Add(animal); } public void Removeanimal(IAnimal animal) { animals.Remove(animal); } public void Aciton() { Console.WriteLine("主人回家了"); foreach (var item in animals) { item.Action(); } } }
调用
Console.WriteLine("观察者模式"); Cat cat = new Cat("Jim"); Dog dog = new Dog("Tom"); Owner owner = new Owner(); owner.Addanimal(cat); owner.Addanimal(dog); owner.Aciton(); Console.WriteLine("观察者模式,委托实现"); Cat cat1 = new Cat("Jim"); Dog dog1 = new Dog("Tom"); OwnerDelegate ownerDelegate = new OwnerDelegate(); ownerDelegate.AddAction(cat1.Action); ownerDelegate.AddAction(dog1.Action); ownerDelegate.Update();
标签:Console,Name,void,观察者,模式,Action,new,public From: https://www.cnblogs.com/daiwk/p/18108443