策略模式(Strategy Pattern)
如下场景:有2类人或者多类人,超人和婴儿,超人会说汉语并且会飞,婴儿不会说并且更不会飞,有一天婴儿长大了就会说英语了,但是不会飞;建立设计模式生成以上两类人(以后可能会是多类人)
设计模式3原则:
1.把变化的与不变化的分开;
2.面向接口编程不要面向实现类编程;
3.多用“组合”少用继承;
实现见代码:
//飞接口 public interface IFly { void Fly(); } //说的接口 public interface ILanguage { void SpeakLanguage(); } //抽象基类 public abstract class People { public IFly Fly; public ILanguage Language; public string Name { get; set; } public void BegainFly() { Fly.Fly(); } public void Speak() { Language.SpeakLanguage(); } public void SetFly(IFly f) { Fly = f; } public void Setlanguage(ILanguage l) { Language = l; } }
针对接口实现类:
class CanFly:IFly { public void Fly() { Console.WriteLine("我会飞!"); } } class CannotFly:IFly { public void Fly() { Console.WriteLine("我不会飞!"); } } public class ChineseLanguage:ILanguage { public void SpeakLanguage() { Console.WriteLine("我说汉语!"); } } class EnglishLanguage:ILanguage { public void SpeakLanguage() { Console.WriteLine("I Speeak English!"); } } class NoEnableSpeakLanguage:ILanguage { public void SpeakLanguage() { Console.WriteLine("我不会说话!"); } }
具体实现人物类: public class SuperMan:People
{ public SuperMan() { Name = "我是超人"; Fly = new CannotFly(); Language = new NoEnableSpeakLanguage(); Console.WriteLine(Name); } } public class Baby:People { public Baby() { Name = "我是婴儿"; Language = new NoEnableSpeakLanguage(); Fly = new CannotFly(); Console.WriteLine(Name); } }
测试一下:
class Program { static void Main(string[] args) { People p = new SuperMan(); p.BegainFly(); p.Speak(); p.SetFly(new CanFly()); p.Setlanguage(new ChineseLanguage()); p.BegainFly(); p.Speak(); p = new Baby(); p.BegainFly(); p.Speak(); Console.ReadKey(); } }
输出结果:
我是超人
我不会飞!
我不会说话!
我会飞!
我说汉语!
我是婴儿
我不会飞!
我不会说话!