3 回答
TA贡献1770条经验 获得超3个赞
接口只是契约或签名,他们对实现一无所知。
public enum Language{ English, German, Spanish}public class SpeakerFactory{ public static ISpeaker CreateSpeaker(Language language) { switch (language) { case Language.English: return new EnglishSpeaker(); case Language.German: return new GermanSpeaker(); case Language.Spanish: return new SpanishSpeaker(); default: throw new ApplicationException("No speaker can speak such language"); } }}[STAThread]static void Main(){ //This is your client code. ISpeaker speaker = SpeakerFactory.CreateSpeaker(Language.English); speaker.Speak(); Console.ReadLine();}public interface ISpeaker{ void Speak();}public class EnglishSpeaker : ISpeaker{ public EnglishSpeaker() { } #region ISpeaker Members public void Speak() { Console.WriteLine("I speak English."); } #endregion}public class GermanSpeaker : ISpeaker{ public GermanSpeaker() { } #region ISpeaker Members public void Speak() { Console.WriteLine("I speak German."); } #endregion}public class SpanishSpeaker : ISpeaker{ public SpanishSpeaker() { } #region ISpeaker Members public void Speak() { Console.WriteLine("I speak Spanish."); } #endregion}
这只是一个基本的例子,对这个原则的实际解释超出了这个答案的范围。
编辑
请注意,我们没有对InterfaceISpeaker做任何更改。客户端代码和SpeakerFactory也保持不变。这就是我们通过 编程到接口 .
public enum Language{ English, German, Spanish}public class SpeakerFactory{ public static ISpeaker CreateSpeaker(Language language) { switch (language) { case Language.English: return new EnglishSpeaker(); case Language.German: return new GermanSpeaker(); case Language.Spanish: return new SpanishSpeaker(); default: throw new ApplicationException("No speaker can speak such language"); } }}class Program{ [STAThread] static void Main() { //This is your client code. ISpeaker speaker = SpeakerFactory.CreateSpeaker(Language.English); speaker.Speak(); Console.ReadLine(); }}public interface ISpeaker{ void Speak();}public abstract class Speaker : ISpeaker{ #region ISpeaker Members public abstract void Speak(); public virtual void SayHello() { Console.WriteLine("Hello world."); } #endregion}public class EnglishSpeaker : Speaker{ public EnglishSpeaker() { } #region ISpeaker Members public override void Speak() { this.SayHello(); Console.WriteLine("I speak English."); } #endregion}public class GermanSpeaker : Speaker{ public GermanSpeaker() { } #region ISpeaker Members public override void Speak() { Console.WriteLine("I speak German."); this.SayHello(); } #endregion}public class SpanishSpeaker : Speaker{ public SpanishSpeaker() { } #region ISpeaker Members public override void Speak() { Console.WriteLine("I speak Spanish."); } public override void SayHello() { throw new ApplicationException("I cannot say Hello World."); } #endregion}
TA贡献1836条经验 获得超4个赞
它隐藏了不需要知道的东西,使对象更易于使用。 它提供了对象将如何运行的契约,因此您可以依赖于此。
- 3 回答
- 0 关注
- 753 浏览
添加回答
举报