設計模式(11)享元模式
阿新 • • 發佈:2018-10-30
tree 們的 http 模式 sign 提高 所有 lin github
模式介紹
享元模式用於創建許多小的、相關的對象,而無需為此調用大量開銷工作,從而提高性能和可維護性。
享元模式允許對象的許多實例共享它們的內在狀態,從而減少與創建它們相關的成本。
示例
我們以Slider(一種類似漢堡的食物)為例。
抽象的享元類
/// <summary> /// The Flyweight class /// </summary> abstract class Slider { protected string Name; protected string Cheese; protected string Toppings; protected decimal Price; public abstract void Display(int orderTotal); }
具體的享元類
/// <summary> /// A ConcreteFlyweight class /// </summary> class BaconMaster : Slider { public BaconMaster() { Name = "Bacon Master"; Cheese = "American"; Toppings = "lots of bacon"; Price = 2.39m; } public override void Display(int orderTotal) { Console.WriteLine("Slider #" + orderTotal + ": " + Name + " - topped with " + Cheese + " cheese and " + Toppings + "! $" + Price.ToString()); } } /// <summary> /// A ConcreteFlyweight class /// </summary> class VeggieSlider : Slider { public VeggieSlider() { Name = "Veggie Slider"; Cheese = "Swiss"; Toppings = "lettuce, onion, tomato, and pickles"; Price = 1.99m; } public override void Display(int orderTotal) { Console.WriteLine("Slider #" + orderTotal + ": " + Name + " - topped with " + Cheese + " cheese and " + Toppings + "! $" + Price.ToString()); } } /// <summary> /// A ConcreteFlyweight class /// </summary> class BBQKing : Slider { public BBQKing() { Name = "BBQ King"; Cheese = "American"; Toppings = "Onion rings, lettuce, and BBQ sauce"; Price = 2.49m; } public override void Display(int orderTotal) { Console.WriteLine("Slider #" + orderTotal + ": " + Name + " - topped with " + Cheese + " cheese and " + Toppings + "! $" + Price.ToString()); } }
工廠類,實例具體的享元類
/// <summary> /// The FlyweightFactory class /// </summary> class SliderFactory { private Dictionary<char, Slider> _sliders = new Dictionary<char, Slider>(); public Slider GetSlider(char key) { Slider slider = null; if (_sliders.ContainsKey(key)) //If we‘ve already created one of the requested type of slider, just use that. { slider = _sliders[key]; } else //Otherwise, create a brand new instance of the slider. { switch (key) { case ‘B‘: slider = new BaconMaster(); break; case ‘V‘: slider = new VeggieSlider(); break; case ‘Q‘: slider = new BBQKing(); break; } _sliders.Add(key, slider); } return slider; } }
客戶端調用
static void Main(string[] args)
{
// Build a slider order using patron‘s input
Console.WriteLine("Please enter your slider order (use characters B, V, Z with no spaces):");
var order = Console.ReadLine();
char[] chars = order.ToCharArray();
SliderFactory factory = new SliderFactory();
int orderTotal = 0;
//Get the slider from the factory
foreach (char c in chars)
{
orderTotal++;
Slider character = factory.GetSlider(c);
character.Display(orderTotal);
}
Console.ReadKey();
}
總結
享元模式通過從一小組“模板”對象中創建大量對象來提高性能,這些對象與所有其他實例相同或非常相似。
源代碼
https://github.com/exceptionnotfound/DesignPatterns/tree/master/Flyweight
原文
https://www.exceptionnotfound.net/flyweight-the-daily-design-pattern/
設計模式(11)享元模式