Flyweight
2022. 3. 11. 00:00ㆍCSharp/Design Pattern
반응형
동일하거나 유사한 객체들 사이에 가능한 많은 데이터를 서로 공유하여 사용하도록 하여 메모리 사용량을 최소화하는 소프트웨어 디자인 패턴이다.
class diagram
예제
public class HeavyObject
{
private readonly string _name;
private readonly int _age;
public HeavyObject(string name, int age)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
_name = name;
_age = age;
}
public void Execution()
{
Console.WriteLine($"Name : {_name} , Age : {_age}, !! Long live Ukraine !! хай живе україна !!");
}
}
public class HeavyObjectFactory
{
private Dictionary<string, HeavyObject> _pool = new Dictionary<string, HeavyObject>();
public HeavyObject Get(string name, int age)
{
string key = $"{name}{age}";
if (!_pool.ContainsKey(key))
{
var obj = new HeavyObject(name,age);
_pool.Add(key, obj);
return obj;
}
return _pool[key];
}
}
사용법
var factory = new HeavyObjectFactory();
var heavyObjects = new List<HeavyObject>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
heavyObjects.Add(factory.Get("Putin", 69));
heavyObjects.Add(factory.Get("Biden", 79));
heavyObjects.Add(factory.Get("Zelensky", 44));
stopwatch.Stop();
Console.WriteLine($"첫번째 초기화시 걸린 시간 {stopwatch.ElapsedMilliseconds}ms");
stopwatch.Restart();
heavyObjects.Add(factory.Get("Biden", 79));
heavyObjects.Add(factory.Get("Putin", 69));
heavyObjects.Add(factory.Get("Zelensky", 44));
stopwatch.Stop();
Console.WriteLine($"두번째 초기화시 걸린 시간 {stopwatch.ElapsedMilliseconds}ms");
foreach (var heavyObject in heavyObjects)
heavyObject.Execution();
// output
첫번째 초기화시 걸린 시간 3034ms
두번째 초기화시 걸린 시간 0ms
Name : Putin , Age : 69, !! Stay strong Ukraine! You will definitely win! !! Будь сильною Укра?но! Ви точно переможете! !!
Name : Biden , Age : 79, !! Stay strong Ukraine! You will definitely win! !! Будь сильною Укра?но! Ви точно переможете! !!
Name : Zelensky , Age : 44, !! Stay strong Ukraine! You will definitely win! !! Будь сильною Укра?но! Ви точно переможете! !!
Name : Biden , Age : 79, !! Stay strong Ukraine! You will definitely win! !! Будь сильною Укра?но! Ви точно переможете! !!
Name : Putin , Age : 69, !! Stay strong Ukraine! You will definitely win! !! Будь сильною Укра?но! Ви точно переможете! !!
Name : Zelensky , Age : 44, !! Stay strong Ukraine! You will definitely win! !! Будь сильною Укра?но! Ви точно переможете! !!
관련영상
반응형
'CSharp > Design Pattern' 카테고리의 다른 글
Chain of Responsibility (0) | 2022.03.14 |
---|---|
Proxy (0) | 2022.03.11 |
Facade (0) | 2022.03.10 |
Decorator (0) | 2022.03.09 |
Composite (0) | 2022.03.08 |