/* This is my own example of the Factory Method pattern. Its principal difference from the example on the patterns website is that it separates the interface from the abstract class. Like Java, C# prohibits multiple-inheritance. You can implement as many interfaces as you want, but you can only inherit code from one class. If you use that class for the purpose of the interface, you would not have the flexibility of inheriting from other classes. */ using System; using System.Collections.Generic; // product/ingridient (abstract items to be produced by factory) public interface ingridient {} public interface topping : ingridient {} // a topping is also an ingredient // concrete product/ingridients: class pepperoni : topping {} class cheese : ingridient {} class tomatosauce : ingridient{} class dough : ingridient {} class sausage : topping {} class mushrooms : topping {} class pineapple : topping {} class bbqchicken : topping {} class greenpeppers : topping {} class canadianbacon : topping {} // "Creator" - the pizza factory interface - every factory must define // makepizza interface pizza { void makepizza(); // can also call this "the factory method" double price(); // other abstract properties of pizzas } // factory dispatch, also makes plain pizza by default. // this is called the abstract creator class plain : pizza // The base superclass { public List A = new List(); // list of ingredients public plain() // dispatches to correct makepizza proc based on dyn. type { A.Add(new dough()); A.Add(new cheese()); A.Add(new tomatosauce()); this.makepizza(); // dispatch to subclass method // ... bake ... Console.WriteLine("pizza with "+A.Count+" ingridients created"); } // default makepizza make a plain cheese pizza public virtual void makepizza() { /* nothing else to do for plain pizza */ } public virtual double price() { return 8.99; } // price of plain pizza } // Concrete Factories: type of these factories is "pizza", while // they inherit the code in "plain" and override the method makepizza. class pepperonipizza : plain, pizza { public override void makepizza() { A.Add( new pepperoni() ); } public override double price() { return 9.99; } } class hawaiian : plain, pizza { public override void makepizza() { A.Add(new canadianbacon()); A.Add(new pineapple()); } public override double price() { return 10.99; } } class veggiepizza : plain, pizza // for vegetarians { public override void makepizza() { A.Add(new mushrooms()); A.Add(new greenpeppers()); } public override double price() { return 9.99; } } public class pizzafactory07 // test client { public static void Main() { pizza p1, p2, p3, p4; p1 = new plain(); p2 = new hawaiian(); p3 = new pepperonipizza(); p4 = new veggiepizza(); double cost = p1.price()+p2.price()+p3.price()+p4.price(); Console.WriteLine("Pay me "+cost+". Bon appetite."); } }