享元模式簡介
使用共享對象可有效地支持大量的細粒度的對象。主要用於減少創建對象的數量,以減少內存佔用和提高性能。這種類型的設計模式屬於結構型模式,它提供了減少對象數量從而改善應用所需的對象結構的方式。
何時使用:
- 系統中有大量對象。
- 這些對象消耗大量內存。
- 這些對象的狀態大部分可以外部化。
- 這些對象可以按照內蘊狀態分爲很多組,當把外蘊對象從對象中剔除出來時,每一組對象都可以用一個對象來代替。
- 系統不依賴於這些對象身份,這些對象是不可分辨的。
大大減少對象的創建,降低系統的內存,使效率提高。
.net中用到享元模式的案例:
- string的駐留池;
- redis, db的連接池;
- 線程池 而不是每次new thread…
- Task -> 寄託在線程池上的線程。
C# 享元模式Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlyweightPattern
{
class Program
{
static void Main(string[] args)
{
FlyWeight flyWeight1 = Factory.CreateInstance(10);
flyWeight1.Run("bob");
FlyWeight flyWeight2 = Factory.CreateInstance(10);
flyWeight2.Run("Andy");
var b = flyWeight1.Equals(flyWeight2);
Console.WriteLine(b);
}
}
public abstract class FlyWeight
{
public abstract void Run(string str);
}
public class ConcreteFlyWeight : FlyWeight
{
public override void Run(string str)
{
Console.WriteLine("{0},你好", str);
}
}
public class UnSharedConcreteFlyWeight : FlyWeight
{
public override void Run(string str)
{
throw new NotImplementedException();
}
}
public class Factory
{
static Dictionary<int, FlyWeight> cache = new Dictionary<int, FlyWeight>();
public static FlyWeight CreateInstance(int num)
{
if (cache.ContainsKey(num))
{
return cache[num];
}
cache.Add(num, new ConcreteFlyWeight());
return cache[num];
}
}
}
測試結果:
參考資料
https://www.bilibili.com/video/av78515440?t=1331&p=20
更多: