private void button1_Click(object sender, EventArgs e) { if (listBox1.SelectedIndex != -1 && listBox2.SelectedIndex != -1) { ICarFactory factory = listBox1.SelectedItem as ICarFactory; ICarType t = listBox2.SelectedItem as ICarType; label1.Text = factory.GetType().Name; if (t is SUV) { ISUV temp = factory.CreateSUV(); label1.Text += " " + temp.OffRoadDriving() + " " + temp.Sell(); } if (t is Hybrid) { IHybrid temp = factory.CreateHybrid(); label1.Text += " " + temp.ChargeCar() + " " + temp.Sell(); } } }
public static void Main(string[] args) { // Register car factories with factory finder CarInstaller.install(); // Access factory finder var finder = FactoryFinder.getInstance(); try { IFactory factory = null; IDiesel dCar = null; IElectric eCar = null; IHybrid hCar = null; factory = finder.findFactory(InterfaceID.ID_Diesel); dCar = (IDiesel)factory.create(); dCar.fuel(); factory = finder.findFactory(InterfaceID.ID_Electric); eCar = (IElectric)factory.create(); eCar.charge(); factory = finder.findFactory(InterfaceID.ID_Hybrid); dCar = (IDiesel)factory.create(); dCar.fuel(); eCar = (IElectric)dCar.getExtension(InterfaceID.ID_Electric); eCar.charge(); factory = finder.findFactory(InterfaceID.ID_Hybridic); hCar = (IHybrid)factory.create(); hCar.fuel(); hCar.charge(); // oder mit Rollenwechsel ICar car = null; factory = finder.findFactory(InterfaceID.ID_Hybrid); // supports only IDiesel und IElectric car = factory.create(); ((IDiesel)car).fuel(); ((IElectric)car).charge(); car = car.getExtension(InterfaceID.ID_Diesel); // Role ID_Diesel ((IDiesel)car).fuel(); car = car.getExtension(InterfaceID.ID_Electric); // Role ID_Electric ((IElectric)car).charge(); // car = car.getExtension(InterfaceID.ID_Hybrid); // UnknownExtensionException: IHybrid not supported // ((IDiesel) car).fuel(); // ((IElectric) car).charge(); // car = car.getExtension(InterfaceID.ID_Hybridic); // UnknownExtensionException: IHybridic not supported // ((IHybrid) car).fuel(); // ((IHybrid) car).charge(); /* Result * * Filled up with Diesel * Charged with Electricity * Filled up with Diesel * Charged with Electricity * Filled up with Diesel * Charged with Electricity * Filled up with Diesel * Charged with Electricity * Filled up with Diesel * Charged with Electricity * */ } catch (UnknownExtensionException ex) { Console.WriteLine(ex); throw; } }