myname0

FlyweightExample

Dec 11th, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. abstract class Candy
  2.     {
  3.         protected string name;
  4.  
  5.         public abstract void Made();
  6.     }
  7.  
  8. class CaramelCandy: Candy
  9.     {
  10.         public CaramelCandy()
  11.         {
  12.             name = "meller";
  13.         }
  14.  
  15.         public override void Made()
  16.         {
  17.             Console.WriteLine("{0} was produced", this.name);
  18.         }
  19.     }
  20.  
  21. class ChocolateCandy: Candy
  22.     {
  23.         public ChocolateCandy()
  24.         {
  25.             name = "milka";
  26.         }
  27.  
  28.         public override void Made()
  29.         {
  30.             Console.WriteLine("{0} was produced", this.name);
  31.         }
  32.     }
  33.  
  34. class CandyFactory
  35.     {
  36.         private Hashtable candys = new Hashtable();
  37.  
  38.         public Candy GetCandy(string key)
  39.         {
  40.             Candy candy = candys[key] as Candy;
  41.             if (candy == null)
  42.             {
  43.                 switch (key)
  44.                 {
  45.                     case "caramel": candy = new CaramelCandy(); break;
  46.                     case "chocolate": candy = new ChocolateCandy(); break;
  47.                 }
  48.                 candys.Add(key, candy);
  49.             }
  50.             return candy;
  51.         }
  52.     }
  53.  
  54. static void Main(string[] args)
  55.         {
  56.             CandyFactory cf = new CandyFactory();
  57.  
  58.             Candy candy1 = cf.GetCandy("caramel");
  59.             candy1.Made();
  60.  
  61.             candy1 = cf.GetCandy("chocolate");
  62.             candy1.Made();
  63.         }
Add Comment
Please, Sign In to add comment