May 30, 2011 Design Patterns
May 30, 2011 Design Patterns
// Abstract expression public abstract class Goods { public abstract int Interpret(CurrentPricesContext context); } // Nonterminal expression public class GoodsPackage : Goods { public List<Goods> GoodsInside { get; set; } public override int Interpret(CurrentPricesContext context) { var totalSum = 0; foreach (var goods in GoodsInside) { totalSum += goods.Interpret(context); } return totalSum; } } // Terminal expression internal class TV : Goods { public override int Interpret(CurrentPricesContext context) { int price = context.GetPrice("TV"); Console.WriteLine("TV: {0}", price); return price; } } // Here other terminal expressions go (Laptop, Bed)
public void RunInterpreterDemo() { // create syntax tree that represents sentence var truckWithGoods = PrepareTruckWithGoods(); // get latest context var pricesContext = GetRecentPricesContext(); // invoke Interpret var totalPriceForGoods = truckWithGoods.Interpret(pricesContext); Console.WriteLine("Total: {0}", totalPriceForGoods); } private CurrentPricesContext GetRecentPricesContext() { var pricesContext = new CurrentPricesContext(); pricesContext.SetPrice("Bed", 400); pricesContext.SetPrice("TV", 100); pricesContext.SetPrice("Laptop", 500); return pricesContext; } public GoodsPackage PrepareTruckWithGoods() { var truck = new GoodsPackage() { GoodsInside = new List<Goods>() }; var bed = new Bed(); var doubleTriplePackedBed = new GoodsPackage() { GoodsInside = new List<Goods>() { new GoodsPackage() { GoodsInside = new List<Goods>() { bed } } } }; truck.GoodsInside.Add(doubleTriplePackedBed); truck.GoodsInside.Add(new TV()); truck.GoodsInside.Add(new TV()); truck.GoodsInside.Add(new GoodsPackage() { GoodsInside = new List<Goods>() { new Laptop(), new Laptop(), new Laptop() } }); return truck; }
Quickly output:
Bed: 400
TV: 100
TV: 100
Laptop: 500
Laptop: 500
Laptop: 500
Total: 2100
Interpreter is one of the design patterns that you most likely will never use in your life. It is bit cumbersome and has very specific application.
Markdown | Result |
---|---|
*text* | text |
**text** | text |
***text*** | text |
`code` | code |
~~~ more code ~~~~ |
more code |
[Link](https://www.example.com) | Link |
* Listitem |
|
> Quote | Quote |
All the patterns have been covered!
Can we expect something about prism in the next post? )
Yeah!!! All are covered! I'm happy as an elephant, that found water in desert.
I guess yes, at the moment we have new subproject that will be build on top of prism. It is new stuff for me and I will definitely have something on it.
Also as I promised I will compose all of the design patterns into one pdf in Ukrainian.
+1 Cool example for this task!
Thank you very much!