访问者模式
关注的是如何对一个集合的成员进行访问
描述了对不同的成员,不同的访问当时,还有不同的处理放生,不同的前置条件
使用场景:把一群if else 封装起来
优点:可以随意添加访问者(Clothes类)
缺点:People类这一层 不能随意增加,必须为确定数量
代码:
人类
public abstract class People
{
public string Name { get; set; }
public string XingBie { get; set; }
public abstract void Say(Clothes cl);
}
public class Nan:People
{
public override void Say(Clothes cl)
{
Console.WriteLine("我是{0},我的性别是:{1}",base.Name,base.XingBie);
cl.Nan_Say();
}
}
public class Nv:People
{
public override void Say(Clothes cl)
{
Console.WriteLine("我是{0},我的性别是:{1}", base.Name, base.XingBie);
cl.Nv_Say();
}
}
访问者父类
public abstract class Clothes
{
public abstract void Nv_Say();
public abstract void Nan_Say();
}
public class DongTianClothes:Clothes
{
public override void Nv_Say()
{
Console.WriteLine("冬天到了,我要穿裤子");
}
public override void Nan_Say()
{
Console.WriteLine("冬天到了,我要穿羽绒服");
}
}
public class ChunTianClothes:Clothes
{
public override void Nv_Say()
{
Console.WriteLine("春天到了,我要穿裙子");
}
public override void Nan_Say()
{
Console.WriteLine("春天到了,我要穿运动装");
}
}
调用:
List<People> peopleList = new List<People>();
People p1 = new Nan()
{
Name="男一号",
XingBie="男"
};
People p2=new Nv(){
Name="女一号",
XingBie="女"
};
peopleList.Add(p1);
peopleList.Add(p2);
foreach (People people in peopleList)
{
people.Say(new DongTianClothes());
}
结果: