1. 程式人生 > >Head First設計模式之享元模式(蠅量模式)

Head First設計模式之享元模式(蠅量模式)

logs sign face isp ria reat 定義 ogr sans

一、定義

享元模式(Flyweight Pattern)主要用於減少創建對象的數量,以減少內存占用和提高性能。這種類型的設計模式屬於結構型模式,它提供了減少對象數量從而改善應用所需的對象結構的方式。

享元模式嘗試重用現有的同類對象,如果未找到匹配的對象,則創建新對象。我們將通過創建 5 個對象來畫出 20 個分布於不同位置的圓來演示這種模式。由於只有 5 種可用的顏色,所以 color 屬性被用來檢查現有的 Circle 對象。

二、結構

技術分享

三、實現

namespace DesignPatterns.Flyweight
{
    class Program
    {
        
static Random ran = new Random(); static Random ranIndex = new Random(); static string[] colors = { "Red", "Green", "Blue", "White", "Black" }; static void Main(string[] args) { for (int i = 0; i < 20; ++i) { Circle circle
= (Circle)ShapeFactory.GetCircle(GetRandomColor()); circle.SetX(GetRandomX()); circle.SetY(GetRandomY()); circle.SetRadius(100); circle.Draw(); } } private static string GetRandomColor() {
int randKey = ranIndex.Next(0, colors.Count() - 1); return colors[randKey]; } private static int GetRandomX() { var d = GetDouble(); return (int)(d * 100); } private static int GetRandomY() { var d = GetDouble(); return (int)(d * 100); } private static double GetDouble() { int randKey = ran.Next(1, 100); return randKey * (1.0) / 100; } } public interface IShape { void Draw(); } public class Circle : IShape { private String color; private int x; private int y; private int radius; public Circle(String color) { this.color = color; } public void SetX(int x) { this.x = x; } public void SetY(int y) { this.y = y; } public void SetRadius(int radius) { this.radius = radius; } public void Draw() { Console.WriteLine("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius); } } public class ShapeFactory { private static Dictionary<String, IShape> circleMap = new Dictionary<String, IShape>(); public static IShape GetCircle(String color) { Circle circle; if (circleMap.ContainsKey(color)) { circle = (Circle)circleMap[color]; } else { circle = new Circle(color); circleMap[color] = circle; Console.WriteLine("Creating circle of color : " + color); } return circle; } } }

四、使用場景

1、系統中有大量對象。

2、這些對象消耗大量內存。

3、這些對象的狀態大部分可以外部化。

4、這些對象可以按照內蘊狀態分為很多組,當把外蘊對象從對象中剔除出來時,每一組對象都可以用一個對象來代替。

5、系統不依賴於這些對象身份,這些對象是不可分辨的。

五、優缺點

優點: 1)享元模式的優點在於它可以極大減少內存中對象的數量,使得相同對象或相似對象在內存中只保存一份。 2)享元模式的外部狀態相對獨立,而且不會影響其內部狀態,從而使得享元對象可以在不同的環境中被共享。 缺點: 1)享元模式使得系統更加復雜,需要分離出內部狀態和外部狀態,這使得程序的邏輯復雜化。 2)為了使對象可以共享,享元模式需要將享元對象的狀態外部化,而讀取外部狀態使得運行時間變長。

Head First設計模式之享元模式(蠅量模式)