static void Main(string[] args) { var supermarket = new SuperMarket(); supermarket.AddProduct("Milk", new Milk(100)); supermarket.AddProduct("Bread",new Bread(250)); var currentMilk = supermarket.GetProduct("Milk"); var currentBread = supermarket.GetProduct("Bread"); var newMilk = (Milk) currentMilk.Clone(); newMilk.Price=120; var newBread = (Bread) currentBread.Clone(); newBread.Price = 245; Console.WriteLine(string.Format("Milk: new ={0} ,old ={1} ",newMilk.Price,currentMilk.Price)); Console.WriteLine(string.Format("Bread: new ={0} ,old ={1} ",newBread.Price,currentBread.Price)); Console.Read(); }
static void Main(string[] args) { var supermarket = new SuperMarket(); supermarket.AddProduct("Milk", new Milk(100)); supermarket.AddProduct("Bread", new Bread(250)); var currentMilk = supermarket.GetProduct("Milk"); var currentBread = supermarket.GetProduct("Bread"); var newMilk = (Milk)currentMilk.Clone(); newMilk.Price = 120; var newBread = (Bread)currentBread.Clone(); newBread.Price = 245; Console.WriteLine(string.Format("Milk: new ={0} ,old ={1} ", newMilk.Price, currentMilk.Price)); Console.WriteLine(string.Format("Bread: new ={0} ,old ={1} ", newBread.Price, currentBread.Price)); Console.Read(); }
private static void Prototype() { // Language agnostic solution var supermarket = new SuperMarket(); supermarket.AddProduct("Milk", new Milk(0.89m)); supermarket.AddProduct("Bread", new Bread(1.10m)); decimal sourcePrice; decimal currentPrice; var clonedMilk = (Milk)supermarket.GetProduct("Milk"); clonedMilk.Price = 1; sourcePrice = supermarket.GetProduct("Milk").Price; currentPrice = clonedMilk.Price; Console.WriteLine(String.Format("{0} | {1}", sourcePrice, currentPrice)); var clonedBread = (Bread)supermarket.GetProduct("Bread"); clonedBread.Price = 2; sourcePrice = supermarket.GetProduct("Bread").Price; currentPrice = clonedBread.Price; Console.WriteLine(String.Format("{0} | {1}", sourcePrice, currentPrice)); // C# specific solution using the ICloneable interface var cloneableProduct = new CloneableProduct(100); var clonedProduct = (CloneableProduct)cloneableProduct.Clone(); clonedProduct.Price = 200; sourcePrice = cloneableProduct.Price; currentPrice = clonedProduct.Price; Console.WriteLine(String.Format("{0} | {1}", sourcePrice, currentPrice)); Console.ReadKey(); }