public static BeepWirelessSpeaker() { WirelessSpeaker w = new WirelessSpeaker(); IBeepSpeakers wirelessSpeakerBeeper = new IBeepSpeakers(w, s => ((WiredSpeaker)s).IsTransmitterOn = true); wirelessSpeakerBeeper.BeepTheSpeaker(); }
public static BeepWirelessSpeaker_Version1() { // This is a valid assignment. Speaker s = new WirelessSpeaker(); IBeepSpeakers wirelessSpeakerBeeper = new IBeepSpeakers(s); // This call will fail! // In WirelessSpeaker, we _OVERRODE_ the Beep method to check // that TransmitterIsOn is true. But, IBeepSpeakers doesn't // know anything _specifically_ about WirelessSpeaker speakers, // so it can't set this property! // Therefore, an InvalidOperationException will be thrown. wirelessSpeakerBeeper.BeepTheSpeaker(); }
public static BeepWirelessSpeaker_Version2() { Speaker s = new WirelessSpeaker(); // I'm using a cast, to show here that IBeepSpeakers is really // operating on a Speaker object. But, this is one way we can // make IBeepSpeakers work, even though it thinks it's dealing // only with Speaker objects. // // Since we set TransmitterIsOn to true, the overridden // Beep method will now execute correctly. // // But, it should be clear that IBeepSpeakers cannot act on both // Speakers and WirelessSpeakers in _exactly_ the same way and // have confidence that an exception will not be thrown. ((WirelessSpeaker)s).TransmitterIsOn = true; IBeepSpeakers wirelessSpeakerBeeper = new IBeepSpeaker(s); // Beep the speaker. This will work because TransmitterIsOn is true. wirelessSpeakerBeeper.BeepTheSpeaker(); }