Use sharing to support large numbers of similar objects efficiently.
通过共享以便有效的支持大量小颗粒对象。
public interface ICoffeeOrder {
void ServeCoffee(CoffeeOrderContext context);
}
public class CoffeeFlavor : ICoffeeOrder {
public string Flavor {
get;
private set;
}
public CoffeeFlavor(string newFlavor) {
this.Flavor = newFlavor;
}
public void ServeCoffee(CoffeeOrderContext context) {
Console.WriteLine("Serving coffee flavor {0} to table {1} .", this.Flavor, context.Table);
}
}
public class CoffeeOrderContext {
public int Table {
get;
private set;
}
public CoffeeOrderContext(int tableNumber) {
this.Table = tableNumber;
}
}
public class CoffeeFlavorFactory {
private readonly IDictionary<string, CoffeeFlavor> _flavors = new Dictionary<string, CoffeeFlavor>();
public CoffeeFlavor GetCoffeeFlavor(string flavorName) {
CoffeeFlavor flavor;
if (this._flavors.TryGetValue(flavorName, out flavor)) {
return flavor;
}
flavor = new CoffeeFlavor(flavorName);
this._flavors.Add(flavorName, flavor);
return flavor;
}
public int TotalFlaversMade {
get {
return this._flavors.Count;
}
}
}
class Program {
private static CoffeeFlavor[] _flavors = new CoffeeFlavor[100];
private static CoffeeOrderContext[] _tables = new CoffeeOrderContext[100];
private static int _ordersMade;
private static CoffeeFlavorFactory _factory;
private static void TakeOrder(string flaver, int table) {
_flavors[_ordersMade] = _factory.GetCoffeeFlavor(flaver);
_tables[_ordersMade++] = new CoffeeOrderContext(table);
}
static void Main(string[] args) {
_factory = new CoffeeFlavorFactory();
TakeOrder("Cappuccino", 2);
TakeOrder("Cappuccino", 2);
TakeOrder("Frappe", 1);
TakeOrder("Frappe", 1);
TakeOrder("Xpresso", 1);
TakeOrder("Frappe", 897);
TakeOrder("Cappuccino", 97);
TakeOrder("Cappuccino", 97);
TakeOrder("Frappe", 3);
TakeOrder("Xpresso", 3);
TakeOrder("Cappuccino", 3);
TakeOrder("Xpresso", 96);
TakeOrder("Frappe", 552);
TakeOrder("Cappuccino", 121);
TakeOrder("Xpresso", 121);
for (int i = 0; i < _ordersMade; i++) {
_flavors[i].ServeCoffee(_tables[i]);
}
Console.WriteLine();
Console.WriteLine("Total CoffeeFlavor objects made {0}", _factory.TotalFlaversMade);
Console.ReadKey();
}
}