观察者模式是使用频率非常非常高的设计模式,在MVC框架中也会经常用到,重中之重,必须掌握!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObservePingPongBall
{
public class Customer:IObserve
{
public string name { get; set; }//定义事件的对象,封装属性
public Customer(string name)
{
this.name = name;
}
public void observer(PlayCry playcry)
{
Console.WriteLine("{0}"+"在观众席看到{1}"+"对她的孩子{2}"+"说,下面的每个人都被{3}"+"{4}过。",name,playcry.name1,playcry.name2,playcry.name3,playcry.action);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObservePingPongBall
{
public class RealPlayCry:PlayCry
{
public RealPlayCry(string name1,string name2,string name3,string action):base(name1,name2,name3,action)
{ }//子类,用于里氏替换原则使用参数
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObservePingPongBall
{
public abstract class PlayCry
{
private List<IObserve> ObserveList = new List<IObserve>();//定义订阅者集合
public string name1 { set; get; }
public string name2 { set; get; }
public string name3 { set; get; }
public string action{ set; get; }
public PlayCry(string name1, string name2,string name3, string action)//定义目标属性
{
this.name1 = name1;
this.name2 = name2;
this.name3 = name3;
this.action = action;
}
public void ObserveAdd(IObserve ob)//添加订阅者
{
ObserveList.Add(ob);
}
public void UpDate()//更新订阅者,将订阅人取出集合,并放入接口方法中
{
foreach (IObserve ob in ObserveList)
{
if (ob != null)
{
ob.observer(this);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObservePingPongBall
{
public interface IObserve
{
void observer(PlayCry playcry);//定义接口方法,将要观察的目标传入方法中
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObservePingPongBall
{
class Program
{
static void Main(string[] args)
{
PlayCry playcrying = new RealPlayCry("张怡宁","xxx","妈妈","打哭");//历史替换,添加具体参数
playcrying.ObserveAdd(new Customer("观众"));//添加具体对象
playcrying.UpDate();//调用,取出订阅
Console.ReadLine();//通过观察者读取
Console.ReadKey();
}
}
}
运行结果: