策略模式
一个父类:
public class People { public IMean MeanWho; public string Name { get; set; } public string Sex { get; set; } }
两个子类Man与Woman有不同的MeanWho:
public class Man:People { public Man() { MeanWho=new ManMean(); } }
public class Woman:People { public Woman() { MeanWho=new WomanMean(); } }
将不同MeanWho独立开来,建立一个超类:
public interface IMean { string Mean(); }
将不同的情况用不同的两个类(ManMean and WomanMean)实现区分:
public class WomanMean:IMean { public string Mean() { Console.WriteLine("Yes"); return null; } }
public class ManMean:IMean { public string Mean() { Console.WriteLine("No"); return null; } }
这样我们就可以轻松的取得Mean
static void Main(string[] args) { People xiaoming=new Man(); People xiaohua=new Woman(); xiaoming.MeanWho.Mean(); xiaohua.MeanWho.Mean(); Console.ReadLine(); }
结果:No
Yes
此设计的好处:
1.如果以后有新的类继承People,而他的Mean也可以轻松的得到不同的Mean;
2.当然还可以多写几个Mean的实现方式,那么Mean的展示就更加多变,我们取Mean的值只要通过People who=new 新类名();轻松的取到。